spring 3 自动装配和 junit 测试 [英] spring 3 autowiring and junit testing
问题描述
我的代码:
@Component
public class A {
@Autowired
private B b;
public void method() {}
}
public interface X {...}
@Component
public class B implements X {
...
}
我想在隔离类 A 中进行测试.我必须模拟 B 类吗?如果是,如何?因为它是自动装配的,并且没有可以发送模拟对象的设置器.
I want to test in isolation class A. Do I have to mock class B? If yes, how? Because it is autowired and there is no setter where i could send the mocked object.
推荐答案
我想在隔离等级 A 中测试.
I want to test in isolation class A.
你绝对应该模拟 B,而不是实例化和注入 B 的实例.重点是测试 A 是否有效,所以你不应该让一个可能损坏的 B 干扰对 A 的测试.
You should absolutely mock B, rather than instantiate and inject an instance of B. The point is to test A whether or not B works, so you should not allow a potentially broken B interfere with the testing of A.
也就是说,我强烈推荐 Mockito.随着模拟框架的发展,它非常易于使用.您将编写如下内容:
That said, I highly recommend Mockito. As mocking frameworks go, it is extremely easy to use. You would write something like the following:
@Test
public void testA() {
A a = new A();
B b = Mockito.mock(B.class); // create a mock of B
Mockito.when(b.getMeaningOfLife()).thenReturn(42); // define mocked behavior of b
ReflectionTestUtils.setField(a, "b", b); // inject b into the B attribute of A
a.method();
// call whatever asserts you need here
}
这篇关于spring 3 自动装配和 junit 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!