让我们看一下这段代码:
public class A {
public void doSmth() { // pay attention - void method
// impl
}
}
public class B {
private A a_instance; // null
public void doSmthElse() {
a_instance.doSmth(); // NPE here without mock
// also do smth. else
}
}
现在,我有
B b = new B();
,我想测试b.doSmthElse()
,但是我需要先为a_instance
对象创建一个模拟,否则我将得到NullPointerException
!如何使用EasyMock或PowerMock实现此目标? 最佳答案
@Test
public void testDoSomething()
{
// setup: sut
B b = new B();
A mockA = EasyMock.createMock(A.class);
b.setA_instance(mockA); // If you have a setter
// setup: expectations
mockA.doSmth();
// exercise
EasyMock.replay(mockA);
b.doSmthElse();
// verify
EasyMock.verify(mockA);
}
@Test
public void testDoSomething_setUsingReflection()
{
// setup: sut
B b = new B();
A mockA = EasyMock.createMock(A.class);
// Set the collaborator using a Spring reflection utility
ReflectionTestUtils.setField(b, "a_instance", mockA);
// setup: expectations
mockA.doSmth();
// exercise
EasyMock.replay(mockA);
b.doSmthElse();
// verify
EasyMock.verify(mockA);
}