春季-如何在针对服务的Spock测试中模拟自动装配的豆子?
作者:互联网
我需要将bean注入服务中才能进行测试.我有这个服务班:
class ContentService {
@Autowired
Evaluator evaluator
...
}
当运行其单元测试副本时,失败的原因是无法找到与Evaluator bean的候选者匹配的bean.我的理解是Grails会为您自动实例化服务变量,但是在这里似乎缺少一些信息来正确地构建它.那将是测试:
@TestFor(ContentService)
class ContentServiceSpec extends Specification {
def setup() {
evaluator = Mock(Evaluator)
service.evaluator = evaluator
}
def "Should test..."() {
...
}
}
似乎无法进行模拟experimentEvaluator并将其手动注入到setup()方法的测试中,因为它失败了:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ExperimentEvaluator] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 28 more
尽管似乎在2.5.0中不再使用它,但我已经看到一些对defineBeans的引用.我无法理解如何使用它,因为Grails测试文档或API文档中都没有对此进行说明.
我也看过doWithSpring,但故事相同:我不知道如何使用它来超越正常用法,而我需要为其创建一个模拟.
我使用Grails 2.5.0.我是Grails的新手,我迷失了它的一些魔力.
解决方法:
您是否尝试过按照规范中的下面所示使用doWithSpring?
import grails.test.mixin.support.GrailsUnitTestMixin
@TestMixin(GrailsUnitTestMixin)
@TestFor(ContentService)
class ContentServiceSpec extends Specification {
static doWithSpring = {
evaluator(Evaluator)
}
def setup() {
service.evaluator = evaluator
}
def "Should test..."() {
...
}
}
有关详细信息,请参考doWithSpring and doWithConfig callback methods, FreshRuntime annotation.
标签:unit-testing,grails,spock,spring 来源: https://codeday.me/bug/20191119/2038286.html