Java单元测试学习(二)
使用测试框架JUnit+Mockito和单元测试覆盖率框架JaCoCo
目录结构
依赖—很好,这里又有个小插曲
打开页面查看覆盖率时一直显示0/0---->最后的解决方式是①添加了maven-surefire-plugin插件
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.7.6version>
<relativePath/>
parent>
<groupId>com.examplegroupId>
<artifactId>mocktioartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>mocktioname>
<description>Demo project for Spring Bootdescription>
<properties>
<maven.compiler.source>11maven.compiler.source>
<maven.compiler.target>11maven.compiler.target>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<testcontainers.version>1.15.3testcontainers.version>
<mockito.version>4.5.1mockito.version>
<junit.version>4.12junit.version>
<commons.version>2.9.0commons.version>
<lombok.version>1.18.12lombok.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.testcontainersgroupId>
<artifactId>testcontainersartifactId>
<version>${testcontainers.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.testcontainersgroupId>
<artifactId>junit-jupiterartifactId>
<version>${testcontainers.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-pool2artifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.mockitogroupId>
<artifactId>mockito-coreartifactId>
<version>${mockito.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mockitogroupId>
<artifactId>mockito-inlineartifactId>
<version>${mockito.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.jacocogroupId>
<artifactId>jacoco-maven-pluginartifactId>
<version>0.8.7version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.19.1version>
plugin>
<plugin>
<groupId>org.jacocogroupId>
<artifactId>jacoco-maven-pluginartifactId>
<version>0.8.6version>
<executions>
<execution>
<id>prepare-agentid>
<goals>
<goal>prepare-agentgoal>
goals>
execution>
<execution>
<id>reportid>
<phase>testphase>
<goals>
<goal>reportgoal>
goals>
execution>
executions>
plugin>
plugins>
build>
project>
相关代码
package com.example.mocktio.dao;
import com.example.mocktio.entity.User;
public interface UserDao {
User getUserByName(String name);
Integer saveUser(User user);
}
package com.example.mocktio.entity;
import lombok.Data;
@Data
public class User {
private String name;
private String sex;
private Integer age;
private String address;
}
package com.example.mocktio.service.impl;
import com.example.mocktio.dao.UserDao;
import com.example.mocktio.entity.User;
import com.example.mocktio.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final UserDao userDao;
@Override
public User getUserByName(String name) {
User userByName = userDao.getUserByName(name);
if (userByName == null) {
log.info("查询结果为空");
throw new RuntimeException("查询结果为空");
}
return userByName;
}
@Override
public Integer saveUser(User user) {
if (userDao.getUserByName(user.getName()) != null) {
throw new RuntimeException("用户存在");
}
try {
return userDao.saveUser(user);
} catch (Exception e) {
throw new RuntimeException("保存用户异常");
}
}
}
package com.example.mocktio.service;
import com.example.mocktio.entity.User;
import org.springframework.stereotype.Service;
@Service
public interface UserService {
User getUserByName(String name);
Integer saveUser(User user);
}
- application.properties为空
- MocktioApplication
package com.example.mocktio;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MocktioApplication {
public static void main(String[] args) {
SpringApplication.run(MocktioApplication.class, args);
}
}
package com.example.mocktio.service.impl;
import com.example.mocktio.MocktioApplicationTests;
import com.example.mocktio.dao.UserDao;
import com.example.mocktio.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
@Slf4j
public class UserServiceTest extends MocktioApplicationTests {
@InjectMocks
private UserServiceImpl userService;
@Mock
private UserDao userDao;
@Test
public void getUserByNameTest1() {
User user = new User();
user.setName("mockName");
user.setSex("mockSex");
user.setAge(18);
user.setAddress("mockAddress");
when(userDao.getUserByName("mockName")).thenReturn(user);
User result = userService.getUserByName("mockName");
verify(userDao).getUserByName(anyString());
Assert.assertNotNull("查询结果为空!", result);
Assert.assertEquals("查询结果错误!", "mockSex", result.getSex());
Assert.assertEquals("查询结果错误!", Integer.valueOf(18), result.getAge());
Assert.assertEquals("查询结果错误!", "mockAddress", result.getAddress());
}
@Test
public void getUserByNameTest2() throws Exception {
when(userDao.getUserByName("mockName")).thenReturn(null);
try {
userService.getUserByName("mockName");
throw new Exception("测试失败");
} catch (RuntimeException e) {
log.info("查询结果为空-测试通过");
}
verify(userDao).getUserByName(anyString());
}
@Test
public void saveUserTest1() throws Exception{
User user = new User();
user.setName("mockName");
when(userDao.getUserByName("mockName")).thenReturn(user);
try {
userService.saveUser(user);
throw new Exception("测试失败");
} catch (RuntimeException e) {
log.info("重复用户名保存失败-测试通过");
}
verify(userDao).getUserByName("mockName");
}
@Test
public void saveUserTest2(){
when(userDao.getUserByName("mockName")).thenReturn(null);
when(userDao.saveUser(any(User.class))).thenReturn(1);
User user = new User();
user.setName("admin");
Integer integer = userService.saveUser(user);
Assert.assertEquals("保存失败!", 1, integer.longValue());
verify(userDao).saveUser(any(User.class));
verify(userDao, times(1)).getUserByName(anyString());
}
}
package com.example.mocktio;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(
classes = MocktioApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@ExtendWith(SpringExtension.class)
public abstract class MocktioApplicationTests {
}
DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="Test Suite" verbose="1">
<test name="Test">
<classes>
<class name="com.example.mocktio.service.impl.UserServiceTest"/>
<class name="com.example.mocktio.MocktioApplicationTests"/>
classes>
test>
suite>
步骤