我想测试以下课程:
public class TestClass {
private OuterClass client;
public TestClass(int v1, String v2){
this.client = new OuterClass.FinalClass(v1, v2).build();
}
public boolean doAThing(){
return this.client.respond();
}
}
我使用的外部库看起来像这样:
public class OuterClass{
private int var1;
private String var2;
private OuterClass(int v1, String v2){
this.var1 = v1;
this.var2 = v2;
}
public static final class FinalClass{
private int v1;
private String v2;
public FinalClass(int v1, String v2){
this.v1 = v1;
this.v2 = v2;
}
public OuterClass build(){
return new OuterClass(this.v1, this.v2);
}
}
public boolean respond(){
throw new IllegalStateException("I'm real and shouldn't be!");
}
}
我的测试代码如下:
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({OuterClass.class, OuterClass.FinalClass.class})
public class TestTest {
@Test
public void test() throws Exception{
PowerMockito.mockStatic(OuterClass.FinalClass.class);
OuterClass.FinalClass mockFinal =
PowerMockito.mock(OuterClass.FinalClass.class);
OuterClass mockOuter = PowerMockito.mock(OuterClass.class);
PowerMockito.whenNew(OuterClass.FinalClass.class)
.withAnyArguments()
.thenReturn(mockFinal);
PowerMockito.when(mockFinal.build()).thenReturn(mockOuter);
Mockito.when(mockOuter.respond()).thenReturn(true);
TestClass t = new TestClass(1, "HALP");
assertTrue(t.doAThing());
}
}
我希望这个测试能够通过,但是它会因为IllegalStateException而失败。它似乎不是像我期望的那样从模拟OuterClass
构建模拟FinalClass
,而是创建一个真实的模拟whenNew
,看起来与我的{{1}}指令相反。我是Mockito和PowerMock的新手,我确信我错过了一些基本的东西。尽管如此,我已经尝试过在SO上找到的每个相关问题的解决方案,但没有一个能够奏效。有谁愿意帮忙吗?
答案 0 :(得分:2)
您还需要准备创建您正在尝试模拟的类的任何类。也就是说,您的注释应该是:
@PrepareForTest({
OuterClass.class,
OuterClass.FinalClass.class,
TestClass.class})