使用Jmockit来mock类的静态方法,网上有很多mock单个类静态方法的例子。有使用Expectations,还有使用MockUp的。
但是如果想在一个测试方法中mock多个类的静态方法,该怎么写呢。
先看mock一个类的静态方法
public class MethodClass { public static String publicStaticMethod() { return "Original public Static Method !"; } public String publicMethod() { return "Original public Method !"; } }
使用Expectations来mock
@Test public void test_mockPublicStatic1() { new Expectations(MethodClass.class) { { MethodClass.publicStaticMethod(); result = "Mocked public static method"; } }; System.out.println(MethodClass.publicStaticMethod());//Mocked public static method MethodClass obj = new MethodClass(); System.out.println(obj.publicMethod());// Original public Method ! }
mock多个类的静态方法,同时传入A.class,B.class。按照期望的顺序录制即可。
new Expectations(A.class,B.class) { { A.publicStaticMethod(); result = "Mocked public static method"; B.publicStaticMethod(); result = "Mocked public static method"; } };