【问题标题】:Mock FileInputStream() with Spock用 Spock 模拟 FileInputStream()
【发布时间】:2022-06-11 15:02:47
【问题描述】:

我有以下方法,我需要用 Spock 编写单元测试。

  private Credentials getCredentials() throws IOException {
    return GoogleCredentials.fromStream(new FileInputStream(gcpKey));
  }

我无法模拟“new FileInputStream(gcpKey)”部分。

到目前为止我尝试过的内容如下。 1.

given: "mock service"

        InputStream inputStream = Mock(InputStream.class)
        
        FileInputStream fileInputStream = Stub(FileInputStream.class){
            new FileInputStream(_) >> inputStream
        }

给定:“模拟服务”

        FileInputStream fileInputStream = GroovySpy(name : "name")
        1 * new FileInputStream("name")

任何人都对此有想法

【问题讨论】:

    标签: java spring-boot unit-testing spock


    【解决方案1】:

    使输入流可注入,然后您可以轻松传入模拟。不要在方法内部创建方法的依赖项。如果没有其他工具,例如 Sarek、Mockito 或过时的 PowerMock,它会使您的代码无法测试。如果您需要此类工具,通常表明您应该重构代码。 TDD 是一种设计工具,而不仅仅是一种用测试覆盖代码的方法。您可能想在 WWW 上搜索“依赖注入”或“控制反转”等术语。

    【讨论】:

      猜你喜欢
      • 2015-08-03
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      相关资源
      最近更新 更多