你想做的是1的一部分和所有2的组合。
您需要使用PowerMockito.mockStatic为类的所有静态方法启用静态模拟。这意味着可以使用when-thenReturn语法存根。
但是mockStatic的2参数重载你使用Mockito / PowerMock应该做的默认策略,当你调用一个方法,你没有显式stub在模拟实例。
Creates class mock with a specified strategy for its answers to
interactions. It’s quite advanced feature and typically you don’t need
it to write decent tests. However it can be helpful when working with
legacy systems. It is the default answer so it will be used only when
you don’t stub the method call.
默认的默认存根策略是为对象,数值和布尔值方法返回null,0或false。通过使用2-arg重载,你说“不,不,不,默认情况下使用这个答案子类’answer方法来获得一个默认值,它返回一个Long,所以如果你有静态方法返回的东西不兼容长,有一个问题。
相反,使用mockStatic的1-arg版本启用静态方法的存根,然后使用when-thenReturn指定对特定方法执行的操作。例如:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
字符串值静态方法被存根以返回“Hello!”,而int值的静态方法使用默认的存根,返回0。