黄同学的后端和 Agent 笔记开通
Hello 后端

动手做:给下单写三层测试,再放三个 bug 进去

黄同学约 11 分钟读完免费

给 ④ 动手做页写好的「创建订单」接口 POST /orders 写三层测试:OrderService 的单元测试、OrderController 的接口测试、连着真 MySQL 的集成测试。全绿以后,往代码里一次放一个 bug,一共三个,看每一层测试各抓住了哪一个。

做完你会看到:同一个 bug,有的测试一眼就抓住,有的测试从头到尾都是绿的,三层测试各管一段,少了哪一层都会漏掉一个。

要先学过:

开始前确认 Docker 开着:docker ps 能打出一个表头,不报错。集成测试会自己用 Docker 起一个 MySQL,测完删掉。

步骤

  1. 起 hello-backend 的 MySQL。Initializr 生成的那个测试 ShopApplicationTests 会把整个项目启动一遍,连的是 application.yml 里写的库:

    bash
    cd hello-backend
    docker compose up -d --wait
  2. 打开 ~/hb-spring/shop/pom.xml,在 <dependencies> 里加三个 Testcontainers 的依赖,只在测试时用,版本都由 parent 管,不用写:

    xml
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-testcontainers</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testcontainers</groupId>
        <artifactId>testcontainers-junit-jupiter</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testcontainers</groupId>
        <artifactId>testcontainers-mysql</artifactId>
        <scope>test</scope>
    </dependency>

    pom.xml 里原来就有一个 spring-boot-starter-webmvc-test(test),是 Initializr 加的,@WebMvcTest、MockMvc、JUnit、Mockito 都在它里面,不用再加;参数校验的 spring-boot-starter-validation 是 ④ 的动手做页加的。改完点 IDEA 右上角的 Maven 小按钮,让它重新读依赖。

  3. 对一下要测的代码。下面这些类都是 ④ 的动手做页写的,测试照它们现在的样子写:

    类 测试用到的地方
    common 包:Result、ErrorCode、BizException、IdGenerator、GlobalExceptionHandler ErrorCode.STOCK_NOT_ENOUGH 是 409、「库存不足」;校验没通过回 400,message 是字段上写的那句
    dto 包:CreateOrderRequest、OrderDTO productId 上有 @NotNull(message = "productId 不能为空");OrderDTO 的 id 以字符串输出
    ProductMapper findById,还有 deductStock(id, quantity),返回改了几行
    OrderMapper insert(order)
    OrderService 构造方法是 OrderService(OrderMapper, ProductMapper, IdGenerator);placeOrder(Long userId, Long productId, int quantity),扣库存改了 0 行时抛 BizException(ErrorCode.STOCK_NOT_ENOUGH)
    OrderController POST /orders,参数前有 @Valid,成功回 201

    没做过 ④ 的动手做页,先照它的第 2 到 7 步和第 10 步把这些类写好。做过后面几个节点的动手做页、往 OrderMapper、OrderService 里加过别的方法的,留着没关系,只要上面这几样还在。

    代码就是这些,下面开始写测试。测试代码都放在 src/test 下面,和 src/main 的包一一对应。

  4. 写单元测试 OrderServiceTest,测两种情况:库存不够时抛 BizException、一条订单都不插;库存够时金额对、插了一次。它不启动 Spring,OrderService 的三个依赖都是 Mock:生成订单号的 IdGenerator 这两条规则用不到,没规定时 nextId() 回 0,不影响结果。

    java
    // src/test/java/com/shop/service/OrderServiceTest.java
    package com.shop.service;
    
    import static org.junit.jupiter.api.Assertions.assertEquals;
    import static org.junit.jupiter.api.Assertions.assertThrows;
    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.Mockito.never;
    import static org.mockito.Mockito.times;
    import static org.mockito.Mockito.verify;
    import static org.mockito.Mockito.when;
    
    import java.math.BigDecimal;
    
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.extension.ExtendWith;
    import org.mockito.Mock;
    import org.mockito.junit.jupiter.MockitoExtension;
    
    import com.shop.common.BizException;
    import com.shop.common.IdGenerator;
    import com.shop.entity.Order;
    import com.shop.entity.Product;
    import com.shop.mapper.OrderMapper;
    import com.shop.mapper.ProductMapper;
    
    @ExtendWith(MockitoExtension.class)
    class OrderServiceTest {
    
        @Mock ProductMapper productMapper;
        @Mock OrderMapper orderMapper;
        @Mock IdGenerator idGenerator;
    
        // 商品 7:机械键盘,单价 299.00
        private Product keyboard() {
            Product p = new Product();
            p.setId(7L);
            p.setName("机械键盘");
            p.setPrice(new BigDecimal("299.00"));
            return p;
        }
    
        @Test
        void stockNotEnough() {
            when(productMapper.findById(7L)).thenReturn(keyboard());
            when(productMapper.deductStock(7L, 2)).thenReturn(0);       // 扣库存改了 0 行
            OrderService service = new OrderService(orderMapper, productMapper, idGenerator);
    
            assertThrows(BizException.class, () -> service.placeOrder(1L, 7L, 2));
            verify(orderMapper, never()).insert(any());                 // 一条订单都没插
        }
    
        @Test
        void stockEnough() {
            when(productMapper.findById(7L)).thenReturn(keyboard());
            when(productMapper.deductStock(7L, 2)).thenReturn(1);       // 扣库存改了 1 行
            OrderService service = new OrderService(orderMapper, productMapper, idGenerator);
    
            Order order = service.placeOrder(1L, 7L, 2);
            assertEquals(new BigDecimal("598.00"), order.getAmount());  // 299.00 × 2
            assertEquals("UNPAID", order.getStatus());
            verify(orderMapper, times(1)).insert(order);
        }
    }
  5. 写接口测试 OrderControllerTest,测三种请求:参数齐全、缺 productId、Service 说库存不足。它只启动 Web 层,OrderService 用 @MockitoBean 换成 Mock:

    java
    // src/test/java/com/shop/controller/OrderControllerTest.java
    package com.shop.controller;
    
    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.ArgumentMatchers.anyInt;
    import static org.mockito.Mockito.never;
    import static org.mockito.Mockito.verify;
    import static org.mockito.Mockito.when;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.bean.override.mockito.MockitoBean;
    import org.springframework.test.web.servlet.MockMvc;
    
    import com.shop.common.BizException;
    import com.shop.common.ErrorCode;
    import com.shop.entity.Order;
    import com.shop.service.OrderService;
    
    @WebMvcTest(OrderController.class)
    class OrderControllerTest {
    
        @Autowired MockMvc mockMvc;
        @MockitoBean OrderService orderService;
    
        @Test
        void created() throws Exception {
            Order order = new Order();
            order.setId(1001L);
            when(orderService.placeOrder(1L, 7L, 2)).thenReturn(order);
    
            mockMvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON)
                            .content("""
                                    {"userId":1,"productId":7,"quantity":2}"""))
                    .andExpect(status().isCreated())
                    .andExpect(jsonPath("$.code").value(0))
                    .andExpect(jsonPath("$.data.id").value("1001"));
        }
    
        @Test
        void missingProductId() throws Exception {
            mockMvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON)
                            .content("""
                                    {"userId":1,"quantity":2}"""))
                    .andExpect(status().isBadRequest())
                    .andExpect(jsonPath("$.code").value(400))
                    .andExpect(jsonPath("$.message").value("productId 不能为空"));
            verify(orderService, never()).placeOrder(any(), any(), anyInt());
        }
    
        @Test
        void stockNotEnough() throws Exception {
            when(orderService.placeOrder(1L, 7L, 2)).thenThrow(new BizException(ErrorCode.STOCK_NOT_ENOUGH));
    
            mockMvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON)
                            .content("""
                                    {"userId":1,"productId":7,"quantity":2}"""))
                    .andExpect(status().isConflict())
                    .andExpect(jsonPath("$.code").value(409))
                    .andExpect(jsonPath("$.message").value("库存不足"));
        }
    }
  6. 写集成测试。先建 src/test/resources/shop.sql,每个测试之前执行一遍,把容器里的库重置成三种商品、零个订单。它只在测试时执行,碰不到你自己的 shop 库:

    bash
    mkdir -p src/test/resources
    sql
    -- src/test/resources/shop.sql
    DROP TABLE IF EXISTS orders;
    DROP TABLE IF EXISTS products;
    
    CREATE TABLE products (
        id    BIGINT AUTO_INCREMENT PRIMARY KEY,
        name  VARCHAR(100),
        price DECIMAL(10,2),
        stock INT
    );
    
    CREATE TABLE orders (
        id         BIGINT PRIMARY KEY,
        user_id    BIGINT,
        product_id BIGINT,
        quantity   INT,
        amount     DECIMAL(10,2),
        status     VARCHAR(20),
        created_at DATETIME
    );
    
    INSERT INTO products (id, name, price, stock) VALUES
        (7, '机械键盘', 299.00, 10),
        (8, '鼠标垫', 39.00, 50),
        (9, '显示器', 1299.00, 5);

    再写 OrderFlowTest:启动整个项目,连上 Testcontainers 起的 MySQL,下单 2 件,再直接查库:

    java
    // src/test/java/com/shop/OrderFlowTest.java
    package com.shop;
    
    import static org.junit.jupiter.api.Assertions.assertEquals;
    import static org.junit.jupiter.api.Assertions.assertNotNull;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.test.context.jdbc.Sql;
    import org.testcontainers.junit.jupiter.Container;
    import org.testcontainers.junit.jupiter.Testcontainers;
    import org.testcontainers.mysql.MySQLContainer;
    
    import com.shop.entity.Order;
    import com.shop.service.OrderService;
    
    @SpringBootTest
    @Testcontainers
    @Sql("/shop.sql")
    class OrderFlowTest {
    
        @Container
        @ServiceConnection
        static MySQLContainer mysql = new MySQLContainer("mysql:8.4.13");
    
        @Autowired OrderService orderService;
        @Autowired JdbcTemplate jdbc;
    
        @Test
        void placeOrderDeductsStock() {
            Order order = orderService.placeOrder(1L, 7L, 2);
    
            int stock = jdbc.queryForObject("SELECT stock FROM products WHERE id = 7", Integer.class);
            int count = jdbc.queryForObject("SELECT COUNT(*) FROM orders", Integer.class);
            assertEquals(8, stock);         // 库存从 10 变成 8
            assertEquals(1, count);         // 多了一个订单
            assertNotNull(order.getId());   // IdGenerator 给了订单号
        }
    }
  7. 跑全部测试:

    bash
    ./mvnw test

    第一次要下载 Testcontainers 的依赖,还要拉 mysql:8.4.13 镜像(以前拉过就不用),会等一会儿。中间会滚过很多日志:两次 Spring Boot 的启动日志(一次是 Initializr 生成的 ShopApplicationTests,一次是 OrderFlowTest),几行 Testcontainers 起容器的日志,可能还有一段 Mockito is currently self-attaching... 的警告,都不用管。最后几行应该是:

    text
    [INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
    [INFO]
    [INFO] BUILD SUCCESS

    7 个测试:单元测试 2 个、接口测试 3 个、集成测试 1 个,加上 Initializr 生成的 1 个。三层测试都写好了,下面开始放 bug,每次只放一个,看完改回去再放下一个。

  8. 第一个 bug:有人觉得扣库存的返回值没用,把 OrderService 里的这一段

    java
    if (productMapper.deductStock(productId, quantity) == 0) {
        throw new BizException(ErrorCode.STOCK_NOT_ENOUGH);
    }

    改成了只有一行:

    java
    productMapper.deductStock(productId, quantity);

    这样库存不够时,UPDATE 一行都没改,代码却接着插了一条订单,超卖了。先别跑,想一想:7 个测试里哪几个会红?想好了再跑 ./mvnw test。

    答案

    只有 OrderServiceTest.stockNotEnough 一个红,最后能看到这样几行(行号以你的为准):

    text
    [ERROR] Failures:
    [ERROR]   OrderServiceTest.stockNotEnough:… Expected com.shop.common.BizException to be thrown, but nothing was thrown.
    [ERROR] Tests run: 7, Failures: 1, Errors: 0, Skipped: 0

    接口测试里 OrderService 是 Mock,根本不执行这段代码;集成测试只测了库存够的情况,库存够时有没有这个 if 结果都一样。只有单元测试专门造了「扣库存改了 0 行」的情况,所以只有它抓得住。

    把这段改回原样。

  9. 第二个 bug:扣库存的 SQL 写错了,不管买几件都只扣 1 件。把 ProductMapper 里 deductStock 上的 SQL 改成:

    java
    @Update("UPDATE products SET stock = stock - 1 WHERE id = #{id} AND stock >= #{quantity}")

    同样先想一想哪几个会红,再跑 ./mvnw test。

    答案

    只有 OrderFlowTest.placeOrderDeductsStock 一个红:

    text
    [ERROR]   OrderFlowTest.placeOrderDeductsStock:… expected: <8> but was: <9>

    买了 2 件,库存只从 10 扣到了 9。单元测试和接口测试里 ProductMapper 都是 Mock,这条 SQL 一次都没执行过,所以它们照样全绿;只有连着真 MySQL 的集成测试,才真的执行了这条 SQL、查出了库存。

    把 stock - 1 改回 stock - #{quantity}。

  10. 第三个 bug:有人改 OrderController 时,把 create 参数前面的 @Valid 删了,写成 @RequestBody CreateOrderRequest req。先想一想,再跑 ./mvnw test。

    答案

    只有 OrderControllerTest.missingProductId 一个红:

    text
    [ERROR]   OrderControllerTest.missingProductId:… Status expected:<400> but was:<500>

    没有 @Valid,缺了 productId 的请求不再被拦下,直接调到了 Mock 的 OrderService。Mock 没被规定过这组参数,返回 null,OrderDTO.from(null) 抛出 NullPointerException,兜底的处理器把它变成了 500,日志里还能看到它打出的「请求处理失败」和调用栈。单元测试不经过 Controller,集成测试直接调 OrderService,都看不到这个 bug。

    把 @Valid 加回去,再跑一次 ./mvnw test,又是 7 个全过。

做完了

三个 bug 各让一个测试变红,改回去以后 ./mvnw test 又是 Tests run: 7, Failures: 0 和 BUILD SUCCESS,就做对了。三个 bug 正好每层测试各抓住一个,另外两层对它都是全绿的,所以三层测试少写哪一层,都会漏掉一种 bug。

Testcontainers 测完会自己删掉 MySQL 容器,用 docker ps -a 看一眼,没有 mysql:8.4.13 的容器留下就对了;拉下来的镜像留着,下次跑测试不用再下载。项目 ~/hb-spring/shop 留着,后面的节点接着用。

做不出来时

  • 集成测试报 Could not find a valid Docker environment:Testcontainers 连不上 Docker。先看 Docker 开着没有,docker ps 能不能用。在 Mac 上用 colima 而不是 Docker Desktop 的,Testcontainers 默认找不到它的 socket,要先设两个环境变量再跑测试:export DOCKER_HOST="unix://${HOME}/.colima/default/docker.sock" 和 export TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock。
  • 接口测试一个都没跑,报 Spring 启动失败,说 OrderController 要一个 OrderService 类型的 Bean 却找不到:@MockitoBean OrderService orderService; 那一行漏了。
  • import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest 标红:pom.xml 里没有 spring-boot-starter-webmvc-test,照 ① 的 pom.xml 加上(<scope>test</scope>)。
  • 还没放 bug,missingProductId 拿到的就是 500 而不是 400:spring-boot-starter-validation 没加,或者 create 参数前的 @Valid 漏了。
  • ShopApplicationTests 报错,日志里有 Communications link failure 或 Access denied for user 'root':它连的是你自己的 MySQL。看第 1 步的 MySQL 起来没有;做过配置的动手做页的,看 application-dev.yml 里有没有 password: ${DB_PASSWORD:secret} 那一行。
  • OrderFlowTest 报 Table 'test.products' doesn't exist:shop.sql 不在 src/test/resources 下面,或者文件名和 @Sql("/shop.sql") 对不上。表名前面的 test 是 Testcontainers 给 MySQL 容器建的库,不是你自己的 shop。
  • 第一次跑卡在拉镜像很久:Testcontainers 在等 Docker 下载 mysql:8.4.13。可以另开一个终端先 docker pull mysql:8.4.13,看得到下载进度,拉好了再跑测试。