JMockit、Mockito和Powermock介绍

   日期:2020-09-21     浏览:98    评论:0    
核心提示:@JMockit、Mockito和PowerMock的区别前言最近看到公司项目里用到了JMockit的框架测试,结合以往使用的Mockito和PowerMock来分析一下三者是如何使用的。一、JMockit使用步骤1. 引入依赖<dependency> <groupId>org.jmockit</groupId> <artifactId>jmockit</artifactId> <version>1.31</v

前言

最近看到公司项目里用到了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;
            }
        };
    }

    
    @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));
    }

    
    @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()));
    }

    
    @Test
    public void testPrivateField(@Injectable final UserDao udao) { 
        Deencapsulation.setField(userService, "books", 2);
        Assert.assertEquals(4, userService.sumBook(2));
    }

    
    @Test
    public void testPrivateMethod(@Injectable final UserDao udao) { 
        Object invoke = Deencapsulation.invoke(userService, "putUsername", "admin");
        Assert.assertEquals("admin", invoke);
    }

    
    @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;

    
    @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> { 

    
    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();
    }

	
    @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)
@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);
    }

    
    @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());
    }

    
    @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());
    }

    
    @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却弥补了这一点,它是无所不能的,正如其名字一样。

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服