代码之家  ›  专栏  ›  技术社区  ›  KIC

spring测试,如何使用`@TestConfiguration模拟方法调用的结果`

  •  0
  • KIC  · 技术社区  · 6 年前

    我有一个bean,它在另一个bean中的某个地方使用,我试图测试它。但是,我不能模拟方法调用,因为它总是说u是未知属性。

    @TestConfiguration
    class IntegrationTestMockingConfig {
        private DetachedMockFactory factory = new DetachedMockFactory()
    
        @Bean
        CloudStorage s3Client() {
            def mockedS3 = factory.Mock(CloudStorage)
            1 * mockedS3.tempDownload(_) >> {
                log.info("mocked s3 client")
                new File(ClassLoader.getSystemResource("testfiles/regular.zip").toURI())
            }
            mockedS3
        }
    
    }
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   E. Hartmann    6 年前

    只需在测试的 setup() -方法。您可以通过向测试中注入依赖项来获得mock。

        2
  •  0
  •   Leonard Brünings    6 年前

    不支持在规范上下文之外进行模拟/存根。我建议使用 @SpringBean

    @SpringBootTest
    class MyTest extends Specification {
    
        @SpringBean
        CloudStorage mockedS3 = Mock() 
    
        def "test"() {
          when:
          otherBean.otherMethod()
    
          then:
            1 * mockedS3.tempDownload(_) >> {
                   log.info("mocked s3 client")
                    new File(ClassLoader.getSystemResource("testfiles/regular.zip").toURI())
            }
        }
    }