0
我有一个类,我想用包含一些链式方法调用的公共静态方法来测试。假设在链式方法调用期间发生异常,我如何有效地处理它并使其返回一些特定的值?嘲笑使用PowerMock链式方法调用
以下是测试类的代码示例。
@RunWith(PowerMockRunner.class)
@PrepareForTest({CodeWithPrivateMethod.class,CodeWithAnotherPrivateMethod.class,CodeWithYetAnotherPrivateMethod.class})
public class CodeWithPrivateMethodTest {
@Test
public void when_gambling_is_true_then_always_explode() throws Exception {
CodeWithYetAnotherPrivateMethod codeWithYetAnotherPrivateMethod = PowerMockito.spy(new CodeWithYetAnotherPrivateMethod());
PowerMockito.whenNew(CodeWithYetAnotherPrivateMethod.class).withAnyArguments().thenReturn(codeWithYetAnotherPrivateMethod);
CodeWithAnotherPrivateMethod codeWithAnotherPrivateMethod = PowerMockito.spy(new CodeWithAnotherPrivateMethod());
PowerMockito.whenNew(CodeWithAnotherPrivateMethod.class).withAnyArguments().thenReturn(codeWithAnotherPrivateMethod);
PowerMockito.doReturn(true).when(codeWithYetAnotherPrivateMethod, "getGambling");
//PowerMockito.doReturn(codeWithYetAnotherPrivateMethod).when(codeWithAnotherPrivateMethod, "getGambleValue");
PowerMockito.spy(CodeWithPrivateMethod.class);
CodeWithPrivateMethod.startGamble();
}
}
以下是该类测试
public class CodeWithPrivateMethod {
public static void startGamble() {
Boolean gamble = CodeWithAnotherPrivateMethod.getGambleValue()
.getGambling();
if (gamble) {
System.out.println("kaboom");
}else{
System.out.println("boom boom");
}
}
}
下面的代码示例是为类的代码示例,但未通过类下的测试,称为
public class CodeWithAnotherPrivateMethod {
static CodeWithYetAnotherPrivateMethod codeWithYetAnotherPrivateMethod = new CodeWithYetAnotherPrivateMethod();
public static CodeWithYetAnotherPrivateMethod getGambleValue() {
return codeWithYetAnotherPrivateMethod; //works fine
return null; // fails
}
}
以下是代码sa mple为其他类,但未通过类测试
public class CodeWithYetAnotherPrivateMethod {
public Boolean getGambling() {
return false;
}
}
称为所以假设我从getGambleValue CodeWithAnotherPrivateMethod类的()方法返回一个空值,我怎么在我的TestClass有效地处理这个空值?
是的,我知道这个事实,但它导致测试用例扔java.lang.AssertionError:预期例外:显示java.lang.NullPointerException。所以可能这不是处理它的正确方法? – isurrender
对不起类名,下次我会照顾的。这就是说我想测试startGamble()方法是否正常工作。而作为CodeWithAnotherPrivateMethod.getGambleValue()------> _returns null_,当调用getGambling()时显然会引发NullPointerException。所以我的问题是我怎么嘲笑** CodeWithAnotherPrivateMethod.getGambleValue() .getGambling()**返回true或false – isurrender
是否有任何此代码可由您修改?我的第一个直觉就是摆脱所有这些静态链接。 –