我试图模拟内部类(Class2.class)的局部变量,但它不起作用。我在下面分享我的代码,请帮我运行第二个testCase。
Class1.java ,其中包含 Class2 作为内部类
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxxx);
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
int restoredLevel = prefs.getInt("level", -1);
if (restoredLevel >-1) { /* continue game*/ }
}
Class3.java
public final class Class1 {
Class2 class2 = new Class2();
public String echoString(String s) {
return class2.echoString2(s);
}
public class Class2 {
public String echoString2(String s) {
Class3 class3 = new Class3(null);
System.out.println("######## Class3 = " + class3);
return class3.getResult(s);
}
}
}
以下是我的TestNG测试用例 我想运行第二个测试用例-pLease help
public class Class3 {
private String data;
public Class3(String data){
this.data=data;
}
public String getResult(String s) {
return data;
}
}
显示错误
@PrepareForTest({ Class1.class, Class2.class, Class3.class })
public class MockTest extends PowerMockTestCase {
String testInput = "input";
String mockedResult = "Mocked - " + testInput;
@InjectMocks
private Class1 tested;
@Mock
Class2 tested2;
@BeforeMethod
public void InjectingMocks() {
MockitoAnnotations.initMocks(this); // Creates a fresh set of mocks
}
@Test
public void mockTest() {
PowerMockito.doReturn(mockedResult).when(tested2)
.echoString2(testInput);
Assert.assertEquals(tested.echoString(testInput), mockedResult);
}
@Test
public void mockTest2() throws Exception {
Class3 c3 = PowerMockito.mock(Class3.class);
PowerMockito.whenNew(Class3.class).withAnyArguments().thenReturn(c3);
PowerMockito.doReturn(mockedResult).when(c3).getResult(testInput);
Assert.assertEquals(tested.echoString(testInput), mockedResult);
}
}
请帮助 - 如果不对实际代码做任何重大更改,我将如何成功运行它。
答案 0 :(得分:0)
怎么样:
@Test
public void mockTest2() throws Exception {
Class3 c3 = PowerMockito.mock(Class3.class);
PowerMockito.whenNew(Class3.class).withAnyArguments().thenReturn(c3);
PowerMockito.doReturn(mockedResult).when(c3).getResult(testInput);
tested = new Class1();
Assert.assertEquals(tested.echoString(testInput), mockedResult);
}
我可能错了,但我认为问题可能是在使用PowerMockito模拟Class3构造函数之前调用了新的Class3(null)。