如何在springboot groovy和spock测试中模拟bean?

问题描述 投票:0回答:1

这是使用 groovy 进行的 spock 测试

这是我的代码

@SpringBootTest
class SrMetricServiceAspectTest extends Specification {
@Autowired
@Qualifier("potentialSrCreation")
private SrCreationService service

@MockBean
SrMetricService srMetricService

@TestConfiguration
static class TestConfig {

    @Bean("potentialSrCreation")
    SrCreationService getSrCreationService() {
        // Return an instance of PotentialSrCreation with necessary dependencies
        return new PotentialSrCreation()
    }
}
}

我对

的结构进行了常规测试
def "..." () {
   given: 
      ...
   when:
      ...
   then:
      ...

但是,当我运行测试时,服务本身为空。我的配置/注入有问题吗?我正在尝试在测试文件中定义 bean。

java spring spring-boot groovy spock
1个回答
0
投票

在 groovy with spock 测试中,您应该使用

@SpringBean
创建模拟并将其注入应用程序上下文

@SpringBootTest
class SrMetricServiceAspectTest extends Specification {

@Autowired
@Qualifier("potentialSrCreation")
private SrCreationService service

@SpringBean
SrMetricService srMetricService

   //write tests

}

使用@SpringBean

在测试上下文中将mock/stub/spy注册为spring bean。

要使用@SpringBean,您必须使用强类型字段定义,否则对象将无法工作。您还需要使用标准 Spock 语法直接将 Mock/Stub/Spy 分配给该字段。您甚至可以使用初始化块来定义常见行为,但是只有在将它们附加到规范后才会选择它们。

@SpringBean 定义可以替换 ApplicationContext 中现有的 Bean。

© www.soinside.com 2019 - 2024. All rights reserved.