在对 Grails 服务进行单元测试时,模拟声明式 REST 客户端的正确方法是什么?
细节
我在我的 Grails 4 应用程序中使用 Micronaut 的声明式 HTTP 客户端。
我尝试使用 Ersatz 对客户端进行单元测试,但几天后我无法让它工作: 如何在 grails 测试环境中配置 Micronaut @Client?
现在,我正在尝试对使用它的服务进行单元测试,使用标准方法来模拟依赖项:
class MyServiceSpec extends Specification implements
ServiceUnitTest<MyService> {
MyRestClient myRestClient = Mock()
def setup() {
service.myRestClient = myRestClient
}
...
}
这给了我一个NoSuchBeanDefinitionException
.
我通过反复试验发现声明式客户端无法与def myRestClient
其他 Grails bean 一样使用。一定是@Autowired
。_
at org.grails.testing.GrailsUnitTest$Trait$Helper.defineBeans(GrailsUnitTest.groovy:99)
at grails.testing.services.ServiceUnitTest$Trait$Helper.mockArtefact(ServiceUnitTest.groovy:58)
at org.grails.testing.ParameterizedGrailsUnitTest$Trait$Helper.getArtefactInstance(ParameterizedGrailsUnitTest.groovy:48)
at grails.testing.services.ServiceUnitTest$Trait$Helper.getService(ServiceUnitTest.groovy:85)
at com.mycompany.MyServiceSpec.setup(MyServiceSpec.groovy:##)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mycompany.MyRestClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1662)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1221)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1175)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:595)
... 15 more