1. 安装 Squaretest 插件
image.png引入 Mockito 依赖
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.0</version>
<scope>test</scope>
</dependency>
2. 自动生成测试类
右击类 -> Generate...
-> Generate Test
选择对应的JUnit版本
image.png
3. 查看单元测试类
@Service
public class GreetServiceImpl implements GreetService {
@Resource
private OrderDao orderDao;
@Override
public String greet() {
Order query = orderDao.query();
int i = 2 + 3;
return "greet";
}
}
生成的单元测试类
import org.mockito.InjectMocks;
import org.mockito.Mock;
@ExtendWith(MockitoExtension.class)
class GreetServiceImplTest {
@Mock
private OrderDao mockOrderDao;
@InjectMocks
private GreetServiceImpl greetServiceImplUnderTest;
@Test
void testGreet() {
// Setup
// Configure OrderDao.query(...).
final Order order = new Order();
order.setId(0);
order.setCode("code");
order.setUserName("userName");
when(mockOrderDao.query()).thenReturn(order);
// Run the test
final String result = greetServiceImplUnderTest.greet();
// Verify the results
assertThat(result).isEqualTo("greet");
}
}
执行单元测试
image.png
4. 查看代码覆盖率
添加依赖
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
</dependency>
配置maven plugin 插件
<build>
<plugins>
<!--使用 jacoco 生成覆盖率报告-->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<configuration>
<includes>
<include>com/**/*</include>
</includes>
</configuration>
<executions>
<execution>
<id>pre-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
执行 maven test
文件目录
.../target/site/jacoco/index.html
网友评论