【问题标题】:Grails unit test fails on @PostConstructGrails 单元测试在 @PostConstruct 上失败
【发布时间】:2014-12-16 21:45:31
【问题描述】:

在服务中有一个@PostConstruct,以确保已设置依赖项。依赖关系在resources.groovy 中设置。 @PostConstruct 断言上的单元测试失败。尝试在setUpSpec 中手动设置依赖项,但无济于事。即使没有@TestFor,ServiceUnitTestMixin 也会在@PostConstruct 上出现并愉快地窒息。 打开了一个缺陷GRAILS-11878,该缺陷立即关闭,并建议使用@FreshRuntime 和doWithSpring。如果他们真的费心去尝试,他们会得到以下错误:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'grails.spring.BeanBuilder$ConfigurableRuntimeBeanReference$WrappedPropertyValue@2cce10bc' with class 'grails.spring.BeanBuilder$ConfigurableRuntimeBeanReference$WrappedPropertyValue' to class 'java.util.Collection' 

正在测试的服务:

@Transactional
class MovieRipIndexService {

    Collection<String> genres

    Collection<String> includes

    @PostConstruct
    void postConstruct() {
        notEmpty(genres as Collection, 'Genres must not be null or empty.')
        notEmpty(includes as Collection, 'Includes must not be null or empty.')
    }
}

测试:

@FreshRuntime
@TestFor(MovieRipIndexService)
class MovieRipIndexServiceSpec extends Specification {

    def doWithSpring = {
        serviceHelper(ServiceHelper)

        service.genres = serviceHelper.genres
        service.includes = serviceHelper.includes
    }
}

【问题讨论】:

    标签: unit-testing grails dependencies postconstruct


    【解决方案1】:

    单元测试中的 Spring 支持相当少,并且处于活动状态的 ApplicationContext 并没有真正经历它在正在运行的应用程序中的任何生命周期阶段,甚至在集成测试的初始化期间。使用 @TestFor 和/或 @Mock 时,您的类中混入了很多功能,但它几乎完全是伪造的,因此您可以专注于对被测类进行单元测试。

    我刚才尝试实现org.springframework.beans.factory.InitializingBean,它奏效了,所以你可能会更进一步。@Transactional 也将被忽略 - “数据库”是ConcurrentHashMap,所以你不会走得太远无论如何。

    如果您需要真正的 Spring 行为,请使用集成测试。单元测试既快速又方便,但仅适用于相当有限的场景。

    【讨论】:

    • 我实际上不需要 Spring 来进行这些测试,这就是我没有编写集成测试的原因。但是,正如我在问题中所写,即使我只是实例化服务类(新)并自己设置依赖项,ServiceUnitTestMixin 也会启动并运行 PostConstruct。如果一切都不是很好。即使没有 TestFor 注释,它也会这样做似乎是一个错误。我不想实现 InitializingBean 接口,因为几年前 Spring 建议不要使用它。这将是一个倒退。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2013-01-27
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多