Mal*_*vin 6 java junit verify suppress powermock
我目前在JUnit测试中遇到困难,需要一些帮助.所以我用静态方法得到了这个类,它将重构一些对象.为简化起见,我举了一个小例子.这是我的工厂类:
class Factory {
public static String factorObject() throws Exception {
String s = "Hello Mary Lou";
checkString(s);
return s;
}
private static void checkString(String s) throws Exception {
throw new Exception();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的Test类:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Factory.class })
public class Tests extends TestCase {
public void testFactory() throws Exception {
mockStatic(Factory.class);
suppress(method(Factory.class, "checkString"));
String s = Factory.factorObject();
assertEquals("Hello Mary Lou", s);
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我试图实现的是私有方法checkString()应该被抑制(因此不抛出异常),并且还需要验证方法checkString()实际上是在方法factorObject()中调用的.
更新:使用以下代码正确抑制:
suppress(method(Factory.class, "checkString", String.class));
String s = Factory.factorObject();
Run Code Online (Sandbox Code Playgroud)
...但是它为String"s"返回NULL.这是为什么?
Mal*_*vin 10
好的,我终于找到了所有问题的解决方案.如果有人遇到类似的问题,这里是代码:
import junit.framework.TestCase;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.times;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {
public void testFactory() throws Exception {
mockStatic(Factory.class, Mockito.CALLS_REAL_METHODS);
suppress(method(Factory.class, "checkString", String.class));
String s = Factory.factorObject();
verifyPrivate(Factory.class, times(1)).invoke("checkString", anyString());
assertEquals("Hello Mary Lou", s);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16904 次 |
| 最近记录: |