08.Mockito示例
Mockito是一个非常好用的mocking框架,它Mockito简单易学,可读性强,验证语法简洁,使用简洁的API完成Mock操作。
本节以简单的示例说明mockito的基本使用。
本示例使用maven构建,所以,请先安装maven环境。
项目结构
项目结构如下:
.
|-- pom.xml
`-- src
|-- main
| |-- java
| | `-- org
| | `-- cloud
| | `-- app
| | |-- entity
| | | `-- User.java
| | |-- main
| | | `-- Main.java
| | |-- rpc
| | | `-- UserRpc.java
| | `-- service
| | `-- UserService.java
| `-- resources
| |-- config.properties
| `-- logback.xml
`-- test
|-- java
| `-- com
| `-- cloud
| `-- app
| `-- service
| `-- UserServiceTest.java
`-- resources
`-- TestConfig.properties
代码列表
/src/main/java/org/cloud/app/entity/User.java
package org.cloud.app.entity;
import java.util.Date;
public class User {
private String userName;
private String realName;
private Date birthday;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
/src/main/java/org/cloud/app/main/Main.java
package org.cloud.app.main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
}
}
/src/main/java/org/cloud/app/rpc/UserRpc.java
package org.cloud.app.rpc;
import org.cloud.app.entity.User;
public class UserRpc {
/**
* 调用远程接口获取用户信息
*
* @return
*/
public User getUser(int id) {
return new User();
}
}
/src/main/java/org/cloud/app/service/UserService.java
package org.cloud.app.service;
import org.cloud.app.entity.User;
import org.cloud.app.rpc.UserRpc;
public class UserService {
private UserRpc userRpc;
public UserRpc getUserRpc() {
return userRpc;
}
public void setUserRpc(UserRpc userRpc) {
this.userRpc = userRpc;
}
/**
* 调用远程接口获取用户信息
*
* @return
*/
public User getUser(int id) {
if (id == 0) {
return null;
}
return userRpc.getUser(id);
}
}
/src/main/resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%class{50} %thread] %-5level %logger{36} | %msg%n" />
<property name="LOG_FOLDER" value="logs" />
<property name="LOG_FILE_NAME" value="logs" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FOLDER}/${LOG_FILE_NAME}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FOLDER}/%d{yyyy-MM,aux}/${LOG_FILE_NAME}.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
<totalSizeCap>500MB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FOLDER}/Error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FOLDER}/%d{yyyy-MM,aux}/Error.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
<totalSizeCap>500MB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<root level="trace">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
</configuration>
/src/test/java/com/cloud/app/service/UserServiceTest.java
package com.cloud.app.service;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Date;
import org.cloud.app.entity.User;
import org.cloud.app.rpc.UserRpc;
import org.cloud.app.service.UserService;
import org.junit.Before;
import org.junit.Test;
public class UserServiceTest {
private UserService userService;
@Before
public void before() {
userService = new UserService();
UserRpc userRpc = mock(UserRpc.class);
User user = new User();
user.setUserName("user1");
user.setRealName("real1");
user.setBirthday(new Date());
when(userRpc.getUser(1)).thenReturn(user);
userService.setUserRpc(userRpc);
}
@Test
public void testGetUser() {
User user = userService.getUser(1);
assertEquals(user.getUserName(), "user1");
assertEquals(user.getRealName(), "real1");
}
}
/pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.cloud.app</groupId>
<artifactId>standard</artifactId>
<packaging>jar</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>standard</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler.version>1.8</compiler.version>
<logback.version>1.2.3</logback.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.name}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${compiler.version}</source>
<target>${compiler.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
代码说明
|-- pom.xml Maven POM
`-- src
|-- main
| |-- java
| | `-- org
| | `-- cloud
| | `-- app
| | |-- entity
| | | `-- User.java 一个实体类,封闭RPC返回
| | |-- main
| | | `-- Main.java 没什么用
| | |-- rpc
| | | `-- UserRpc.java 只一个getUser模拟调用远程rpc返回一个User对象
| | `-- service
| | `-- UserService.java 服务层,调用RPC返回User
| `-- resources
| |-- config.properties 空文件,可以不要
| `-- logback.xml logback配置
`-- test
|-- java
| `-- com
| `-- cloud
| `-- app
| `-- service
| `-- UserServiceTest.java 真正有用的类,UserService的测试类
`-- resources
`-- TestConfig.properties 空文件,可以不要
运行
进入项目目录 执行maven clean test
输出如下:
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------------< org.cloud.app:standard >-----------------------
[INFO] Building standard 1.0.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ standard ---
[INFO] Deleting E:\sts\standard\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ standard ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ standard ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 4 source files to E:\sts\standard\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ standard ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ standard ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to E:\sts\standard\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ standard ---
[INFO] Surefire report directory: E:\sts\standard\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.cloud.app.service.UserServiceTest
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.mockito.cglib.core.ReflectUtils$2 (file:/C:/Users/Cloud.F.Strife/.m2/repository/org/mockito/mockito-all/1.10.19/mockito-all-1.10.19.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.mockito.cglib.core.ReflectUtils$2
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.252 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.757 s
[INFO] Finished at: 2019-01-05T15:15:47+08:00
[INFO] ------------------------------------------------------------------------
如下首次运行 mvn
命令,会有大量的下载,请等待。