当前位置: 首页 > 工具软件 > JMockit > 使用案例 >

JMockit、Mockito和Powermock介绍

郑帅
2023-12-01

前言

最近看到公司项目里用到了JMockit的框架测试,结合以往使用的Mockito和PowerMock来分析一下三者分别是如何使用的。


一、JMockit使用

1. 引入依赖

<dependency>
	<groupId>org.jmockit</groupId>
	<artifactId>jmockit</artifactId>
	<version>1.31</version>
	<scope>test</scope>
</dependency>

<!-- 此依赖用于注解@BeforeMethod和@Test -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
</dependency>

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.11</version>
	<scope>test</scope>
</dependency>

2. @Mocked与@Injectable

关于二者的区别,这篇博客JMokit中的@Mocked与@Injectable区别说得比较详细,这里不再赘述。需要注意的是对于静态方法和构造方法,@Injectable并不起作用,而@Mocked照样起作用。另外,@Injectable与@Tested是搭配使用的,如果使用了@Tested和@Mocked集合,会报错,因为@Tested找不到@Injectable注解的实例去初始化构造方法(亲测),可通过测试方法@Injectable实例化参数来解决。

3. JMockit的record(录制)---- replay(回放) ---- verify(验证)

package com.demo.core.jmockit;

import com.demo.api.bean.dto.BookBaseDto;
import com.demo.api.bean.po.User;
import com.demo.api.service.IBuyBookService;
import com.demo.core.Service.UserService;
import com.demo.core.dao.UserDao;
import com.demo.core.utils.DateUtils;
import mockit.*;
import org.junit.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.text.ParseException;
import java.util.*;


public class TestCase {

    @Mocked
    private UserDao userDao;

    @Injectable
    private IBuyBookService buyBookService;

    //@Tested注解的不是interface,而是具体实现类
    @Tested
    private UserService service;

    private UserService userService;

    //在测试方法之前运行
    @BeforeMethod
    private void setUp() {
        userService = new UserService();
    }

    @Test
    public void testQueryUserListByUsername(@Injectable final UserDao udao) {
        final List<User> userList = Collections.singletonList(new User("admin", "pwd123", 25));
        //对于一些类的私有成员属性可以通过设值的方式来注入
        Deencapsulation.setField(userService, "userDao", userDao);
        //录制脚本
        new Expectations() {
            {
                //需要录制的方法调用
                userDao.selectUserListByUserName(anyString);
                //录制的返回结果
                result = userList;
            }
        };

        //回放阶段
        List<User> users = userService.queryUserListByUsername("admin");
        Assert.assertEquals(1, users.size());

        //验证阶段(匿名内部类)
        new Verifications() {
            {
                userService.queryUserListByUsername(anyString);
                //调用次数
                times = 1;
            }
        };
    }

    /**
     * mockUp
     * 当我们只需要mock某个类的某一个方法,对于其他方法我们正常调用
     */
    @Test
    public void testMockUp(@Injectable final UserDao udao) {
        new MockUp<UserService>() {
            @Mock
            public String viewUsername(String username) {
                return "guest";
            }
        };
        Assert.assertEquals("guest", userService.viewUsername("admin"));
        Assert.assertEquals(23, userService.viewAge(23));
    }

    /**
     * JMockit的另一个强大之处,可以mock静态方法(功能和PowerMock有的一比)
     */
    @Test
    public void testStaticMethod(@Injectable final UserDao udao) throws ParseException {
        final String currentTime = "2020-09-20 15:40:00";
        new Expectations(DateUtils.class) {
            {
                DateUtils.dateToString((Date) any);
                result = currentTime;
            }
        };
        Assert.assertEquals(currentTime, DateUtils.dateToString(new Date()));
    }

    /**
     * mock私有属性
     */
    @Test
    public void testPrivateField(@Injectable final UserDao udao) {
        Deencapsulation.setField(userService, "books", 2);
        Assert.assertEquals(4, userService.sumBook(2));
    }

    /**
     * mock私有方法
     */
    @Test
    public void testPrivateMethod(@Injectable final UserDao udao) {
        Object invoke = Deencapsulation.invoke(userService, "putUsername", "admin");
        Assert.assertEquals("admin", invoke);
    }

    /**
     * 模拟@Test和@Injectable集合使用
     */
    @Test
    public void testCalculatePrice(@Injectable final UserDao udao) {
        new Expectations() {
            {
                buyBookService.doBookPrice((BookBaseDto) any);
                result = 48.00;
                times = 1;
            }
        };
        Deencapsulation.setField(service, "books", 2);
        Object price = service.calculatePrice();
        Assert.assertEquals(96.00, price);
    }

}

UserService代码如下:

@Service
@Slf4j
public class UserService implements IUserService {

    @Autowired
    private UserDao userDao;

    private int books;

    @Override
    public List<User> queryUserListByUsername(String username) {
        List<User> userList = userDao.selectUserListByUserName(username);
        if (CollectionUtils.isEmpty(userList)) {
            log.warn("查询用户信息为空");
            return null;
        }
        return userList;
    }

    @Override
    public int updateUserByParams(User user) {
        List<User> userList = userDao.selectUserListByUserName(user.getUsername());
        if (CollectionUtils.isEmpty(userList)) {
            log.warn("根据用户名" + user.getUsername() + "查询用户信息为空...");
            return 0;
        }
        return userDao.updateUserByParams(user);
    }

    @Override
    public String viewUsername(String username) {
        return username;
    }

    @Override
    public int viewAge(int age) {
        return age;
    }

    public int sumBook(int count) {
        int myCount = this.buyBook();
        return myCount + count;
    }

    private int buyBook(){
        return this.books;
    }

    private String putUsername(String username) {
        return username;
    }
	
	public double calculatePrice() {
        BookBaseDto baseDto = AnimationBook.builder()
                .bookName("动物世界")
                .animationPrice(20)
                .build();
        Object price = buyBookService.doBookPrice(baseDto);
        return (double) price * this.books;
    }
}

DateUtils代码如下:

@Slf4j
public class DateUtils {
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static String dateToString (Date date) throws ParseException {
        if (date == null) {
            return null;
        }
        synchronized (dateFormat) {
            return dateFormat.format(date);
        }
    }
}

一般来说@Capturing不经常使用,下面单独举例说明一下,其中AnimationBookService和MythologyBookService分别实现IMemberStrategyService接口。

package com.demo.core.jmockit;

import com.demo.api.bean.dto.AnimationBook;
import com.demo.api.bean.dto.MythologyBook;
import com.demo.api.service.IMemberStrategyService;
import com.demo.core.Service.AnimationBookService;
import com.demo.core.Service.MythologyBookService;
import mockit.Capturing;
import mockit.Expectations;
import org.junit.Assert;
import org.testng.annotations.Test;

public class TestCapturing {

    @Capturing
    private IMemberStrategyService memberStrategyService;

    /**
     * 模拟@Capturing
     */
    @Test
    public void testCapturing() {
        IMemberStrategyService animationBookService = new AnimationBookService();
        IMemberStrategyService mythologyBookService = new MythologyBookService();
        new Expectations() {
            {
                memberStrategyService.calcPrice(any);
                result = 40.00;
            }
        };
        Object animationPrice = animationBookService.calcPrice(AnimationBook.builder().bookName("动物世界").animationPrice(20).build());
        Object mythologyPrice = mythologyBookService.calcPrice(MythologyBook.builder().bookName("神话故事").mythologyPrice(10).build());

        //不管IMemberStrategyService的实现类是哪个,计算的价格都是40.00
        Assert.assertEquals(40.00, animationPrice);
        Assert.assertEquals(40.00, mythologyPrice);
    }
}
package com.demo.api.service;

public interface IMemberStrategyService<T> {

    /**
     * 计算图书的价格
     * @param bookType 不同的图书
     * @return 计算出打折后的价格
     */
    double calcPrice(T bookType);
}

JMockit小结:

  1. 对@Tested对象判断是否为null,是则通过合适构造器初始化, @Injectable的实例会自动注入到@Tested中。

  2. 当只知道父类或接口,但需要控制它所有子类的行为时,子类可能有多个实现,就用@Capturing。

  3. MockUp只能模拟类,不能模拟接口


二、Mockito使用

1. 引入依赖

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.10.19</version>
    <scope>test</scope>
</dependency>

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.11</version>
	<scope>test</scope>
</dependency>

2. 举例说明

首先引入MockMvc,对模块进行集成测试时,希望能够通过输入URL对Controller进行测试,如果通过启动服务器,建立http client进行测试,这样会使得测试变得很麻烦,比如,启动速度慢,测试验证不方便,依赖网络环境等,所以为了可以对Controller进行测试,我们引入了MockMVC。因为Mockito和PowerMock的使用方式基本一样,所以具体使用和下面的PowerMock一起说明。

package com.ssm.web.controller;

import com.google.common.collect.Lists;
import com.ssm.po.User;
import com.ssm.service.IUserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.util.List;

import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-application-context.xml", "classpath:test-spring-mvc.xml"})
public class LoginUserControllerTest {

    private MockMvc mockMvc;

    @InjectMocks//创建一个实例,其余用@Mock(或@Spy)注解创建的mock将被注入到用该实例中
    private static LoginUserController loginUserController;

    @Mock
    private IUserService userService;

    @Before
    public void before() {
    	//不适用@Mock注解也可以使用如下方式mock
    	//userService = mock(IUserService.class);
        //这句话执行以后,userService自动注入到loginUserController中。
        //在这之后,你就可以放心大胆地使用when().then()等进行更详细的设置
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(loginUserController).build();
    }

	/**
     * MockMvc方法解析
     * perform:执行一个RequestBuilder请求,会自动执行SpringMvc的流程并映射到相应的控制器执行处理
     * get:声明发送一个get请求方法。MockHttpServletRequestBuilder get(Sring urlTemple, Object… urlVariables):根据url模板和url变量值得到一个GET请求方式的。另外提供了其他的请求方法,如:POST、PUT、DELETE等
     * param:添加request的参数,如上面发送请求的时候戴上了pcode=root的参数。假如使用需要发送json数据格式的时候将不能使用这种方式。
     * andExpect:添加ResultMatcher验证规则,验证控制器执行完成后结果是否正确(对返回的数据进行的判断)
     * andDo:添加ResultHandler结果处理器,比如调试时打印结果到控制台(对返回的数据进行的判断)
     * andReturn:最后返回相应的MvcResult:然后进行自定义验证/进行下一步异常处理(对返回的数据进行的判断)
     * contentType 指定org.springframework.http.MediaType 指定请求参数类型json之类的
     * @throws Exception
     */
    @Test
    public void testCheckLoginUser() throws Exception{
        List<User> userList = Lists.newArrayList();
        User user = new User();
        user.setAge(10);
        user.setUsername("Jay Chen");
        user.setPassword("admin");
        userList.add(user);

        Mockito.when(userService.queryUserListByUsername(Mockito.anyString())).thenReturn(userList);
        mockMvc.perform(get("/cf/queryUserList")
                .param("username", "chen"))
                .andExpect(status().isOk())
                .andReturn();
        verify(userService).queryUserListByUsername(Mockito.anyString());
    }
}

Mockito小结:

  1. 在单元测试中使用@Mock, @Spy, @InjectMocks等注解时,需要进行初始化后才能使用。

  2. MockitoAnnotations.initMocks(this),其中this就是单元测试所在的类,在initMocks函数中Mockito会根据类中不同的注解(如@Mock, @Spy等)创建不同的mock对象,即初始化工作


三、PowerMock使用

1. 引入依赖

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.7.4</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.7.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.10.19</version>
    <scope>test</scope>
</dependency>

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.11</version>
	<scope>test</scope>
</dependency>

一般情况下,PowerMock结合Mockito一起使用。需要注意的是,PowerMock和Mockito会存在jar包版本的冲突,详情可见此链接。(https://www.linkedin.com/pulse/mockito-2x-over-powermock-migration-tips-tricks-top-ten-hazem-saleh?trk=seokp-post-title)

2. 举例说明

package com.demo.core.powermock;

import com.demo.api.bean.po.User;
import com.demo.api.service.IBuyBookService;
import com.demo.api.service.IUserService;
import com.demo.core.Service.UserService;
import com.demo.core.dao.UserDao;
import com.demo.core.utils.DateUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import org.springframework.test.util.ReflectionTestUtils;

import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;



/**
 * @RunWith(PowerMockRunner.class)语句告诉JUnit用PowerMockRunner来执行测试。
 * @PrepareForTest(DateUtils.class)语句告诉PowerMock准备DateUtils类进行测试。
 * 适用于模拟final类或有final, private, static, native方法的类。
 **/
@RunWith(PowerMockRunner.class)
@PrepareForTest({DateUtils.class})//如果注解在某个测试方法上,单个的测试类会初始化错误(亲测)
public class UserServiceTest {

    private IUserService userService;

    @Mock
    private UserDao userDao;

    @Mock
    private IBuyBookService buyBookService;

    @Before
    public void setUp() {
        userService = new UserService();
        userDao = PowerMockito.mock(UserDao.class);
        ReflectionTestUtils.setField(userService, "userDao", userDao);

        buyBookService = PowerMockito.mock(IBuyBookService.class);
        ReflectionTestUtils.setField(userService, "buyBookService", buyBookService);
    }

    /**
     * 一般使用方式
     * @throws Exception
     */
    @Test
    public void testQueryUserListByUsername() throws Exception {
        List<User> userList = Arrays.asList(new User("chen", "admin", 25), new User("fei", "24", 24));
        PowerMockito.when(userDao.selectUserListByUserName(Mockito.anyString())).thenReturn(userList);
        //测试抛出异常
        //PowerMockito.when(userDao.selectUserListByUserName(Mockito.anyString())).thenThrow(new RuntimeException());
        List<User> users = userService.queryUserListByUsername("chen");
        Assert.assertEquals(2, users.size());
    }

    /**
     * 静态方法mock
     * @throws ParseException
     */
    @Test
    public void testStaticMethod() throws ParseException {
        String date = "2020-09-20 15:40:00";
        PowerMockito.mockStatic(DateUtils.class);
        PowerMockito.when(DateUtils.dateToString(Mockito.any((Date.class)))).thenReturn(date);
        Assert.assertEquals(date, userService.getTime());
    }

    /**
     * mock私有属性
     */
    @Test
    public void testPrivateField() throws IllegalAccessException {
        PowerMockito.field(UserService.class, "books").set(userService, 2);
        Assert.assertEquals(2, userService.viewBooks(1));
    }

    /**
     * 测试私有方法一
     */
    @Test
    public void testPrivateMethod() throws Exception {
        //此种方式一般在public或protected方法中mock私有方法
        //PowerMockito.doReturn("admin").when(userService, "putUsername", "admin");

        //第一个参数是私有方法所在类,第二个参数是私有方法名,第三个参数是私有方法参数
        Method method = PowerMockito.method(UserService.class, "putUsername", String.class);
        Object invoke = method.invoke(userService, "admin");
        Assert.assertEquals("admin", invoke);
    }

    /**
     * 测试私有方法二
     */
    @Test
    public void testPrivateMethod_2() throws Exception {
        Object obj = Whitebox.invokeMethod(userService, "putUsername", "admin");
        Assert.assertEquals("admin", obj);
    }

}

总结

从上面JMockit和PowerMock的举例来看,二者的功能非常相似,用法也很相近。都可以对静态方法或属性以及对私有方法进行mock。不过可以看到,JMockit的使用比起PowerMock更加轻量级,不需要对类进行整个注解,只需在单个测试用例中使用即可。PowerMock相当于是Mockito的升级版,Mockito不能实现对静态方法的mock,而PowerMock却弥补了这一点,它是无所不能的,正如其名字一样。

 类似资料: