Easymock 调用自动装配的对象方法
Easymock call autowired object method
假设我关注了 类:
public class A {
@Autowired B b;
public void doSomething(){
b.doSomeThingElse();
}
@Component
@Autowired C c;
public class B {
public void doSomethingElse(){
c.doIt();
}
当你知道我想模拟 c.doIt()
但想用 EasyMock 调用 b.doSomethingElse();
时,我如何测试 A?
提前致谢
@Autowired
很好,但往往会让我们忘记如何测试。只需为 b
和 c
添加一个 setter。
C c = mock(C.class);
c.doIt();
replay(c);
B b = new B();
b.setC(c);
A a = new A();
a.setB(b);
a.doSomething();
verify(c);
或者使用构造函数注入。
C c = mock(C.class);
c.doIt();
replay(c);
B b = new B(c);
A a = new A(b);
a.doSomething();
verify(c);
在这种情况下,您的 类 变为:
public class A {
private B b;
public A(B b) { // Spring will autowired by magic when calling the constructor
this.b = b;
}
public void doSomething() {
b.doSomeThingElse();
}
}
@Component
public class B {
private C c;
public B(C c) {
this.c = c;
}
public void doSomethingElse(){
c.doIt();
}
}
假设我关注了 类:
public class A {
@Autowired B b;
public void doSomething(){
b.doSomeThingElse();
}
@Component
@Autowired C c;
public class B {
public void doSomethingElse(){
c.doIt();
}
当你知道我想模拟 c.doIt()
但想用 EasyMock 调用 b.doSomethingElse();
时,我如何测试 A?
提前致谢
@Autowired
很好,但往往会让我们忘记如何测试。只需为 b
和 c
添加一个 setter。
C c = mock(C.class);
c.doIt();
replay(c);
B b = new B();
b.setC(c);
A a = new A();
a.setB(b);
a.doSomething();
verify(c);
或者使用构造函数注入。
C c = mock(C.class);
c.doIt();
replay(c);
B b = new B(c);
A a = new A(b);
a.doSomething();
verify(c);
在这种情况下,您的 类 变为:
public class A {
private B b;
public A(B b) { // Spring will autowired by magic when calling the constructor
this.b = b;
}
public void doSomething() {
b.doSomeThingElse();
}
}
@Component
public class B {
private C c;
public B(C c) {
this.c = c;
}
public void doSomethingElse(){
c.doIt();
}
}