我想从包含2个静态方法m1和m2的类中模拟静态方法m1.我希望方法m1返回一个对象.
我尝试了以下内容
1)
PowerMockito.mockStatic(Static.class, new Answer<Long>() {
@Override
public Long answer(InvocationOnMock invocation) throws Throwable {
return 1000l;
}
});
Run Code Online (Sandbox Code Playgroud)
这是调用m1和m2,它们具有不同的返回类型,因此它给出了返回类型不匹配错误.
2)PowerMockito.when(Static.m1(param1, param2)).thenReturn(1000l);
但是当执行m1时不会调用它.
3)PowerMockito.mockPartial(Static.class, "m1");
给出了mockPartial不可用的编译错误,这是我从http://code.google.com/p/powermock/wiki/MockitoUsage获得的.
我正在设置一个类的静态方法.我必须在@Before注释的JUnit设置方法中执行此操作.
我的目标是设置类来调用实际方法,除了我明确模拟的那些方法.
基本上:
@Before
public void setupStaticUtil() {
PowerMockito.mockStatic(StaticUtilClass.class);
// mock out certain methods...
when(StaticUtilClass.someStaticMethod(anyString())).thenReturn(5);
// Now have all OTHER methods call the real implementation??? How do I do this?
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,在StaticUtilClass方法中,public static int someStaticMethod(String s)不幸的是抛出一个RuntimeExceptionif null值.
所以我不能简单地将调用真实方法的明显路线作为默认答案,如下所示:
@Before
public void setupStaticUtil() {
PowerMockito.mockStatic(StaticUtilClass.class, CALLS_REAL_METHODS); // Default to calling real static methods
// The below call to someStaticMethod() will throw a RuntimeException, as the arg is null!
// Even …Run Code Online (Sandbox Code Playgroud)