java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Junit5在IDEA中快速使用

Junit5在IDEA中快速使用详解

作者:Gao_xu_sheng

本文介绍了如何在IDEA中使用Maven进行JUnit5测试类的创建,并详细说明了生成测试类时各个选项的含义,同时,还提供了若依框架下Controller和Service的标准测试模板

一、POM引用  

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

有些框架引用后可能会显示junit3,不会切换到5

右侧 Maven 面板 → 点击:

Reload All Maven Projects

等依赖下载完。

如果还是不行,执行:

File → Invalidate Caches / Restart

然后重启 IDEA。

二、快速生成测试类

创建测试类的方式是:

光标放在类名上 → 快捷键生成测试

1、打开你要测试的类

例如:CalcService.java

2、光标放在类名上

public class CalcService {

3、按快捷键

4、选择

Create New Test...

三、弹窗选项

1、Testing library

JUnit5

2、Class name

EwisePReportControllerTest

3、Superclass

extends TestCase

4、Destination package

com.ruoyi.report.controller

比如:

src/main/java/com/ruoyi/report/controller

测试必须在:

src/test/java/com/ruoyi/report/controller

IDEA 默认帮你处理好了,不用改。

5、Generate → setUp / tearDown

@BeforeEach
@AfterEach

6、Show inherited methods

7、Generate test methods for(最容易误解的)

下面一堆:

list()
getInfo()
add()
edit()
remove()
...

是干嘛的?

帮你生成“空测试方法”:

@Test
void list() {
}

只是生成一个壳子。

要不要勾?

建议:

否则会变成:

@Test void list(){}
@Test void getInfo(){}
@Test void add(){}
...

四、若依 Controller 标准测试模板

假设你的 Controller 是:

@RequestMapping("/report")
@RestController
public class EwisePReportController {

标准测试类(推荐写法)

package com.ruoyi.report.controller;

import com.ruoyi.RuoYiApplication;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest(classes = RuoYiApplication.class)
@AutoConfigureMockMvc
class EwisePReportControllerTest {

    @Autowired
    private MockMvc mockMvc;

    /**
     * 测试列表接口(返回 TableDataInfo)
     */
    @Test
    void list_shouldReturnSuccess() throws Exception {
        mockMvc.perform(get("/report/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.total").exists())
                .andExpect(jsonPath("$.rows").exists());
    }

    /**
     * 测试详情接口(返回 AjaxResult)
     */
    @Test
    void getInfo_shouldReturnAjaxResult() throws Exception {
        mockMvc.perform(get("/report/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").exists())
                .andExpect(jsonPath("$.msg").exists());
    }

    /**
     * 测试新增接口(POST)
     */
    @Test
    void add_shouldReturnSuccess() throws Exception {
        String json = """
                {
                  "name": "测试报表",
                  "remark": "测试数据"
                }
                """;

        mockMvc.perform(post("/report")
                        .contentType("application/json")
                        .content(json))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

}

如果你开启了 Spring Security(若依默认开启)

如果接口被权限拦截,会 401 或 403。

解决方式:

方法一(简单粗暴测试)

@SpringBootTest(classes = RuoYiApplication.class)
@AutoConfigureMockMvc(addFilters = false)

addFilters = false = 关闭安全过滤器(测试环境用)

方法二(更规范)

加:

@WithMockUser

例如:

@Test
@WithMockUser(username = "admin")
void list_shouldReturnSuccess() throws Exception {

需要引入:

import org.springframework.security.test.context.support.WithMockUser;

若依三种常见返回结构断言写法

1、AjaxResult 结构

若依标准结构:

{
  "code": 200,
  "msg": "操作成功",
  "data": {}
}

断言写法:

.andExpect(jsonPath("$.code").value(200))
.andExpect(jsonPath("$.msg").exists())

2、TableDataInfo 结构

{
  "total": 10,
  "rows": [...]
}

断言:

.andExpect(jsonPath("$.total").isNumber())
.andExpect(jsonPath("$.rows").isArray())

3、导出接口(Excel)

@Test
void export_shouldReturnFile() throws Exception {
    mockMvc.perform(post("/report/export"))
            .andExpect(status().isOk())
            .andExpect(header().exists("Content-Disposition"));
}

五、若依Service标准测试模板(重点)

典型若依 Service 结构

@Service
public class EwisePReportServiceImpl implements IEwisePReportService {

    @Autowired
    private EwisePReportMapper reportMapper;

    @Override
    public List<EwisePReport> selectEwisePReportList(EwisePReport report) {
        return reportMapper.selectEwisePReportList(report);
    }

    @Override
    public int insertEwisePReport(EwisePReport report) {
        report.setCreateTime(new Date());
        return reportMapper.insertEwisePReport(report);
    }
}

标准写法 1:纯单元测试

模板

package com.ruoyi.report.service;

import com.ruoyi.report.domain.EwisePReport;
import com.ruoyi.report.mapper.EwisePReportMapper;
import com.ruoyi.report.service.impl.EwisePReportServiceImpl;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class EwisePReportServiceTest {

    @Mock
    private EwisePReportMapper reportMapper;

    @InjectMocks
    private EwisePReportServiceImpl reportService;

    /**
     * 测试查询列表
     */
    @Test
    void selectList_shouldReturnData() {
        EwisePReport query = new EwisePReport();

        when(reportMapper.selectEwisePReportList(query))
                .thenReturn(List.of(new EwisePReport()));

        List<EwisePReport> result =
                reportService.selectEwisePReportList(query);

        assertNotNull(result);
        assertEquals(1, result.size());

        verify(reportMapper, times(1))
                .selectEwisePReportList(query);
    }

    /**
     * 测试新增时是否自动设置时间
     */
    @Test
    void insert_shouldSetCreateTime() {
        EwisePReport report = new EwisePReport();

        when(reportMapper.insertEwisePReport(report))
                .thenReturn(1);

        int rows = reportService.insertEwisePReport(report);

        assertEquals(1, rows);
        assertNotNull(report.getCreateTime());

        verify(reportMapper, times(1))
                .insertEwisePReport(report);
    }
}

写复杂逻辑时的测试模板

如果你有这种逻辑:

public int calcDiff(Integer first, Integer last) {
    if (first == null || last == null) {
        return 0;
    }
    return last - first;
}

测试写法:

@Test
void calcDiff_normal() {
    int result = reportService.calcDiff(3, 10);
    assertEquals(7, result);
}

@Test
void calcDiff_null() {
    int result = reportService.calcDiff(null, 10);
    assertEquals(0, result);
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文