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

How to mock bean in springboot groovy and spock tests?

提问人:committedandroider 提问时间:11/13/2023 最后编辑:Ryuzaki Lcommittedandroider 更新时间:11/13/2023 访问量:54

问:

这是一个使用 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:
      ...

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

java spring-boot groovy spock

评论

0赞 Peng 11/13/2023
1. 确保应用程序运行在 Spring 环境中,2.如果应用程序在 Spring 上下文中,请尝试使用 Spring 提供的而不是 .我认为应用程序更有可能不在春季模式下@AutoWiredMockBean

答:

0赞 Ryuzaki L 11/13/2023 #1

在 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您必须使用强类型字段 def 否则 Object 将不起作用。您还需要使用标准 Spock 语法直接将 Mock/Stub/Spy 分配给字段。您甚至可以使用初始值设定项块来定义常见行为,但是只有在将它们附加到规范后才会选择它们。

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