让我们看一下这段代码:
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实现这一目标?
答案 0 :(得分:1)
@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);
}
答案 1 :(得分:0)
您可以使用
instanceName.methodName();
Easymock.expectLastCall(); //for void methods this is how it is done
instanceName可以是mocked或actualInstance。
如果你可以使方法保持静态,那么使用powermock会更容易
Powermock.mockStatic(ClassNameContainingStaticMethod)
直接模拟所有静态方法
注意事项: - 将方法转换为静态可能会在其他部分出现问题。请小心
希望它有所帮助。 一切顺利!
答案 2 :(得分:-1)
我认为这里不需要PowerMock的原因。您可以通过EasyMock实现这一目标。
@Test
public void testDoSmthElse() {
A a = EasyMock.createMock(A.class);
EasyMock.expect(a.doSmth()).andReturn(/*some value */);
EasyMock.replay(a);
B b = new B();
Object whatever = b.doSmthElse();
assert(); // psuedo-line. Add whatever assertion required
}
注意:导入适当的类