Practical
code examples:
1. Introduce dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
引入spring-boot-starter-test依赖就好,因为此版本的框架中默认集成了Junit4和Mockito。
2. Introduce the plug-in TestMe
Note
: This plug-in cannot be searched for versions before idea2021.3.3.
3. Writing unit test code
Use TestMe to automatically generate unit test code:
public class UserServiceImplTest {
//创建模拟对象
@Mock
UserManager userManager;
//注入mock对象
@InjectMocks
UserServiceImpl userServiceImpl;
@Before
public void setUp() {
//使@Mock和@InjectMocks对象生效
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetUserByUid() throws Exception {
User user = new User();
user.setUid(2055755111L);
user.setCountryId(1);
//设置模拟对象的行为
when(userManager.getUserByUid(111L)).thenReturn(user);
//执行代码
User user = userServiceImpl.getUserByUid(111L);
//断言结果是否符合预期
Assert.assertNotNull(user);
}
}
public class UserServiceImpl{
@Autowired
UserManager userManager;
public User getUserByUid(Long uid) {
//Some logics
User user = userManager.getUserByUid(111L);
//Another logics
}
}
4. Automate unit testing
Unit tests that are not executed automatically are meaningless. There are so many unit tests in the project, are they one by one?
Introduce the maven-surefire-plugin plug-in for automated execution of single tests.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<includes>
<include>com.user.service.UserServiceImpl</include>
</includes>
</configuration>
</plugin>
Include represents the single test class that needs to be executed. A large number of classes can be defined, such as: **/*Tests.java (all Java files ending with "Test").
Execute maven command:
mvn clean test 先清除旧的编译项目,在运行test内容。
Under surefire-reports under the target, you can see the single test report just run.
5. Generate test rate coverage report
Order:
mvn cobertura:cobertura
You can see the coverage report in index.html under site.
It probably looks like this: