JMockit涉及到的元素介绍:
@Tested和@Injectablepackage com.zero.jmockit; public class Utils { private static String URL_STRING = "http://www.sina.com.cn"; private static void deal() { System.out.println("deal() " + URL_STRING); } public static String getObject(JMockitObject object, String str) { deal(); System.out.println("getObject() "); return URL_STRING + str; } }
package com.zero.jmockit; public class UserService { public String getUserName(int id) { return "hello"; } }
package com.zero.jmockit; import javax.annotation.Resource; public class JMockitObject { @Resource private UserService userService; public void dealUser() { String name = userService.getUserName(1); System.out.println("userService.getUserName() : " + name); sys(name); } private void sys(String name) { System.out.println("sys() : " + name); } public String getString() { getObject(this, "/zero"); return Utils.getObject(this, "/zero"); } private void getObject(JMockitObject object, String str) { System.out.println("--------"); } }
package com.zero.jmockit; import org.junit.*; import org.junit.runner.RunWith; import mockit.*; import mockit.integration.junit4.JMockit; @RunWith(JMockit.class) public final class JMockitTest { @Tested @Mocked private JMockitObject jMockitObject; @Injectable private UserService userService; @Test public void testDealUser() { new NonStrictExpectations() {// 录制预期模拟行为 { userService.getUserName(anyInt);//mock public方法 result = "zero";// 也可以使returns("zero"); times = 1; Deencapsulation.invoke(jMockitObject, "sys", anyString);//mock private方法 // sys()无返回值,没定义result,则调用的结果返回空,故result = null; 可写可不写 result = null; } }; jMockitObject.dealUser();//回放 } @Test public void testSys() { Deencapsulation.invoke(jMockitObject, "sys", "Hello World!");//测试private方法 } @Test public void testStaticField() {// mock 静态私有属性 new NonStrictExpectations(Utils.class) { { Deencapsulation.setField(Utils.class, "URL_STRING", "www.baidu.com"); } }; // 第二种方式: // new MockUp<Utils>() { // { // // 修改静态私有属性 // Deencapsulation.setField(Utils.class, "URL_STRING", // "www.baidu.com"); // } // }; String str = Deencapsulation.getField(Utils.class, "URL_STRING"); Assert.assertEquals("www.baidu.com", str); } @Test public void testStaticFunction() {// mock 静态私有方法 new MockUp<Utils>() { @Mock private void deal() {// 注意在MockUp中的方法除了不包含static关键字以外,其他都和被Mock的方法签名相同,并且使用@Mock标注 System.out.println("mock deal() "); } }; Deencapsulation.invoke(Utils.class, "deal"); } @Test public void testGetString() { new NonStrictExpectations() { { Deencapsulation.invoke(jMockitObject, "getObject", withAny(JMockitObject.class), withAny(String.class));// 不能使用any这样的参数,否则必须使用正确类型的参数; // withAny(JMockitObject.class), anyString); 可以 } }; new NonStrictExpectations(Utils.class) { { Utils.getObject((JMockitObject) any, anyString); returns("zero"); } }; Assert.assertEquals("zero", jMockitObject.getString()); } }