本文主要是介绍Junit,Mockito,PowerMockito 进行单元测试,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
编写不易,转载请注明( http://shihlei.iteye.com/blog/2383925)!
概述:
介绍基于Junit ,Mockito,PowerMockito 常用的测试方法,包括异常测试,私有方法测试,没有返回值的方法测试,基于mock或spy的测试;
其中包含常规方法mock,私有方法mock。
一 测试介绍
1)测试原则:
凡是需要验证的方法都可以写单元测试,证明预期行为(不区分 controller,service ,dao)
2)测试分类:
a)单元测试:测试方法的 “逻辑” 是否满足期望。
b)集成测试:集成各个依赖组件,测试整体流程是否能通。
3)关于依赖:
单元测试一般测试当前方法的逻辑,不测试被依赖的类方法或自己的私有方法。
4)Mock 和 Spy 生成类区别
Mock:生成的类,所有方法都不是真实的方法,而且返回值都是NULL; 通过when 指定行为。
Spy:生成的类,所有方法都是真实方法,返回值都是和真实方法一样的;通过when 来将某个真实的方法,替换为指定行为的执行。
5)参考
1)普通mockito mock
http://site.mockito.org/
2)使用powerMock ,增强 静态方法,私有方法能力;
https://github.com/powermock/powermock
二 Demo 本程序依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>x.test</groupId><artifactId>test</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><name>test</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><junit.version>4.12</junit.version><mockito.version>2.8.47</mockito.version><powermock.version>1.7.0</powermock.version><assertj.version>3.8.0</assertj.version></properties><dependencies><!-- test --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><scope>test</scope></dependency><dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><version>${mockito.version}</version><scope>test</scope></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-module-junit4</artifactId><version>${powermock.version}</version><scope>test</scope></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-api-mockito2</artifactId><version>${powermock.version}</version><scope>test</scope></dependency><dependency><groupId>org.assertj</groupId><artifactId>assertj-core</artifactId><version>${assertj.version}</version><scope>test</scope></dependency><!-- utils --><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>20.0</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build> </project>
三 简单的测试
测试抛异常,无返回值的方法测试,私有方法测试
1)被测试类
package x.test.simple;import com.google.common.base.Strings;/**
* 测试demo class
* <p>
* Created by shilei on 2017/7/10.
*/
public class HelloWho {private String who;public HelloWho(String who) {//条件路径if (Strings.isNullOrEmpty(who)) {throw new IllegalArgumentException("who can not be null!");}//赋值路径this.who = who;}public void sayHello() {System.out.println(getHelloMessage());}private String getHelloMessage() {return "Hello " + who;}
}
2)测试类
package x.test.simple;import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.powermock.reflect.Whitebox;/*** 基础测试:* <p>* 1 测试抛异常* 2 测试无返回值* 3 测试私有方法*/
public class HelloWhoTest {@Test(expected = IllegalArgumentException.class)public void test_construction_empty_who_throw_exception() {new HelloWho("");}@Test(expected = IllegalArgumentException.class)public void test_construction_null_who_throw_exception() {new HelloWho(null);}/*** 无返回值的方法测试,查看其修改的成员变量是否成功*/@Testpublic void test_construction_args_set_who() throws Exception {//预期结果String expectWho = "A";//执行被测试方法HelloWho helloWho = new HelloWho(expectWho);//白盒,获取修改的成员变量String actualWho = (String) Whitebox.getField(helloWho.getClass(), "who").get(helloWho);//断言Assertions.assertThat(actualWho).isEqualTo(expectWho);}/*** 测试私有方法*/@Testpublic void test_getHelloMessage() throws Exception {//准备方法参数String who = "A";//准备预期结构String expextMessage = "Hello " + who;//执行被测试方法HelloWho helloWho = new HelloWho(who);String actualMessage = Whitebox.invokeMethod(helloWho, "getHelloMessage");//断言Assertions.assertThat(actualMessage).isEqualTo(expextMessage);}}
四 基于Mock的测试
依赖mock,私有方法mock,验证方法是否被执行
1)被依赖类Dao
package x.test.adv.dao.pojo;/**
* 用户
* <p>
* Created by shilei on 2017/7/10.
*/
public class User {}package x.test.adv.dao;import x.test.adv.dao.pojo.User;/**
* 用户dao
* Created by shilei on 2017/7/10.
*/
public interface UserDao {/*** 保存** @param user 用户* @return true : 保存成功 ; false : 用户已存在*/boolean save(User user);
}
2)待测试类Service
package x.test.adv.service;import x.test.adv.dao.pojo.User;/**
* 用户服务
* <p>
* Created by shilei on 2017/7/10.
*/
public interface UserService {/*** 保存 , 如果保存成功,记录日志** @param user user*/void save(User user);
}package x.test.adv.service.impl;import x.test.adv.dao.UserDao;
import x.test.adv.dao.pojo.User;
import x.test.adv.service.UserService;/**
* 带依赖的测试
* <p>
* Created by shilei on 2017/7/10.
*/
public class UserServiceImpl implements UserService {private UserDao userDao;@Overridepublic void save(User user) {//保存boolean isSave = userDao.save(user);//写大数据日志if (isSave) {writeLog(user);}}private void writeLog(User user) {System.out.println(user);}}
3)测试类
package x.test.adv.service.impl;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.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import x.test.adv.dao.UserDao;
import x.test.adv.dao.pojo.User;/**
* 带依赖的测试:
* 1 mock 依赖
* 2 mock 私有方法
*/
@RunWith(PowerMockRunner.class)
//mock 静态方法,私有方法,需要添加该注解,以便通知框架
@PrepareForTest(UserServiceImpl.class)
public class UserServiceImplTest {//mock 依赖注入到该bean@InjectMocksprivate UserServiceImpl userServiceImpl;//mock 依赖@Mockprivate UserDao userDao;//完成依赖注入@Beforepublic void setUp() {MockitoAnnotations.initMocks(this);}/*** 测试保存成功,写日志*/@Testpublic void test_save_true_verify_writelog() throws Exception {// 侦查对象UserServiceImpl spyUserService = PowerMockito.spy(userServiceImpl);//创建输入User user = new User();//打桩// mock 依赖行为,等价于 BDDMockito.given(userDao.save(user)).willReturn(true);Mockito.when(userDao.save(user)).thenReturn(true);//mock 私有方法PowerMockito.doNothing().when(spyUserService, "writeLog", user);//调用实际方法spyUserService.save(user);//断言 writelog 被执行一次PowerMockito.verifyPrivate(spyUserService, Mockito.times(1)).invoke("writeLog", user);}/*** 测试保存成功,写日志*/@Testpublic void test_save_false_no_writelog() throws Exception{// 侦查对象UserServiceImpl spyUserService = PowerMockito.spy(userServiceImpl);//创建输入User user = new User();//打桩// mock 依赖行为,等价于 BDDMockito.given(userDao.save(user)).willReturn(true);Mockito.when(userDao.save(user)).thenReturn(false);//mock 私有方法PowerMockito.doNothing().when(spyUserService, "writeLog", user);//调用实际方法spyUserService.save(user);//断言 writelog 被执行一次PowerMockito.verifyPrivate(spyUserService, Mockito.times(0)).invoke("writeLog", user);}
}
这篇关于Junit,Mockito,PowerMockito 进行单元测试的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!