代码发布在链接
现在,当我试图写junit为第一种情况,我得到错误
"需要重放B类".
,但同样的junit也适用于第二种情况。
my junit is
@RunWith(PowerMockRunner.class)
public class TestClass {
@Test
public void testDoSomeThing() {
B b = createMock(B.class)
expectNew(b.CallMe()).andReturns(xxx)
A a=new A();
replayAll();
a.doSomething();
verifyAll();
}
}
下面是使用EasyMock和PowerMock的解决方案:
TestClass.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ A.class, B.class })
public class TestClass {
@Test
public void testDoSomeThing() throws Exception {
/* Setup */
B bMock = PowerMock.createMock(B.class);
/* Mocks */
PowerMock.expectNew(B.class).andReturn(bMock).atLeastOnce();
bMock.callMe();
/* Activate */
PowerMock.replayAll();
/* Test */
A cut = new A();
cut.doSomething();
/* Asserts */
PowerMock.verifyAll();
}
}
A.java
public class A {
B b = new B();
public void doSomething() {
b.callMe();
}
}
B.java
public class B {
public void callMe() {
}
}
你忘了添加
@PrepareForTest({A.class, B.class})
该注释必须包含您正在模拟的类和将使用这些模拟的类。