Aar*_*ron 17 java unit-testing mockito
我正在尝试模拟私有静态方法anotherMethod().见下面的代码
public class Util {
public static String method(){
return anotherMethod();
}
private static String anotherMethod() {
throw new RuntimeException(); // logic was replaced with exception.
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试代码
@PrepareForTest(Util.class)
public class UtilTest extends PowerMockTestCase {
@Test
public void should_prevent_invoking_of_private_method_but_return_result_of_it() throws Exception {
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.class, "anotherMethod").thenReturn("abc");
String retrieved = Util.method();
assertNotNull(retrieved);
assertEquals(retrieved, "abc");
}
}
Run Code Online (Sandbox Code Playgroud)
但是我运行它的每个瓷砖都得到了这个例外
java.lang.AssertionError: expected object to not be null
Run Code Online (Sandbox Code Playgroud)
我想我在做嘲弄事情时做错了.任何想法我该如何解决?
tro*_*oig 36
为此,您可以使用PowerMockito.spy(...)和PowerMockito.doReturn(...).此外,您必须在测试类中指定PowerMock运行程序,如下所示:
@PrepareForTest(Util.class)
@RunWith(PowerMockRunner.class)
public class UtilTest {
@Test
public void testMethod() throws Exception {
PowerMockito.spy(Util.class);
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod");
String retrieved = Util.method();
Assert.assertNotNull(retrieved);
Assert.assertEquals(retrieved, "abc");
}
}
Run Code Online (Sandbox Code Playgroud)
希望它能帮到你.
如果anotherMethod()将任何参数作为anotherMethod(参数),则方法的正确调用将是:
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22605 次 |
| 最近记录: |