如何JUnit测试包含@Autowired @Session作用域依赖项的Spring Bean

时间:2011-11-10 10:23:54

标签: spring junit

我已经看到链接Spring Test session scope bean using Junit,它显示了如何设置Junit来测试@Session范围的bean,但是我如何设置一个Junit测试用例来测试一个带有@Session范围bean的Spring bean @自动加入其中。

1 个答案:

答案 0 :(得分: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
   }
}