【问题标题】:How to JUnit test a Spring Bean that contains an @Autowired @Session scoped dependancy如何 JUnit 测试包含 @Autowired @Session 范围依赖的 Spring Bean
【发布时间】:2011-11-10 10:23:54
【问题描述】:

我看到了链接Spring Test session scope bean using Junit,它显示了如何设置 Junit 来测试 @Session 范围的 bean,但是我如何设置 Junit 测试用例来测试具有 @Session 范围的 bean @Autowired 的 Spring bean它。

【问题讨论】:

  • 此链接的解决方案也适用于您的情况。

标签: spring junit


【解决方案1】:

如果您正在测试 spring bean 的行为,最简单的方法是模拟对象并使用 ReflectionTestUtils 自己注入:

class SpringBean {
    @Autowired Other other;

    public void method() {
        // ...
    }
}

class SpringBeanTest {
   @Test public void testIt() {
       Other other = new Other();
       SpringBean bean = new SpringBean();
       ReflectionTestUtils.setField(bean, "other", other);
       // test it
   }
}

【讨论】:

    猜你喜欢
    • 2011-07-05
    • 2015-08-30
    • 2018-07-19
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    相关资源
    最近更新 更多