配置 PIT 对 MyBatis Mapper 接口进行变异测试。

解读

国内互联网与金融企业普遍要求单元测试覆盖率 ≥ 80%,但高覆盖率≠高可靠性。变异测试(Mutation Testing) 通过植入“缺陷种子”验证测试用例能否真正发现问题,是晋升评审、代码评审时的“硬核指标”。MyBatis 的 Mapper 接口只有方法签名,真正的 SQL 逻辑藏在 XML/注解里,传统 PIT 默认只能对 Java 字节码插桩,无法直接感知 SQL 变化,因此必须做“二次配置”:既要让 PIT 识别 Mapper 接口,又要让变异算子作用到 SQL 节点,还要保证 Spring 容器、MyBatis 映射、嵌入式数据库三者同时启动。面试官问这道题,重点不是背步骤,而是考察候选人是否理解“半自动化 ORM”与“字节码变异”之间的断层,以及如何用国内主流技术栈(Spring Boot + H2 + Maven)闭环验证。

知识点

  1. PIT 运行模型:在 javac 之后、Surefire 之前,通过 ASM 对 class 做 27 种常规变异(AOR、ROR、COD、INLINE 等),再跑单元测试,统计“杀死率”。
  2. MyBatis 动态代理:Mapper 接口在运行时由 MapperProxyFactory 生成 JDK 动态代理,真实执行体是 MappedStatement 里的 SQL,字节码层面只有代理转发逻辑,所以默认变异对 SQL 无效。
  3. SQL 变异算子:国内自研扩展(阿里 Pandora、美团 MTS)提供 SQLI、SQLO、SQLC 三类算子,分别对条件、列、排序做变异;开源方案可借用 MyBatis-Plus 的 SQLInjector 自定义 MappedStatement,再让 PIT 对 SqlNode 做文本级变异。
  4. 嵌入式数据库:H2 模式兼容 MySQL 8 语法,Maven 生命周期 pre-integration-test 启动 TCP 模式,保证 PIT 多线程 fork 时连接池不崩。
  5. Spring Boot 测试切片:@MybatisTest 只注入 DataSource+SqlSessionFactory,不启动 Web 容器,节省 60% 启动时间,符合国内“单测必须 3 秒以内”的潜规则。
  6. 增量变异:pitest-git-plugin 结合 git diff,只对本次 MR 修改的 Mapper 做变异,CI 流水线 5 分钟以内出报告,否则会被领导毙掉。

答案

步骤以 Maven 多模块工程 order-center 为例,源码目录 src/main/java,测试目录 src/test/java,Mapper XML 放在 src/main/resources/mapper。

  1. 引入依赖(版本锁定,国内源)
<properties>
    <pitest.version>1.15.0</pitest.version>
    <mybatis.version>3.5.13</mybatis.version>
    <h2.version>2.2.220</h2.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.pitest</groupId>
        <artifactId>pitest-junit5-plugin</artifactId>
        <version>1.2.0</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>${h2.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>
  1. 配置 Surefire 先跑单元测试
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.1.2</version>
    <configuration>
        <includes>
            <include>**/*MapperTest.java</include>
        </includes>
    </configuration>
</plugin>
  1. PIT 插件配置:指定变异目标、输出格式、线程数
<plugin>
    <groupId>org.pitest</groupId>
    <artifactId>pitest-maven</artifactId>
    <version>${pitest.version}</version>
    <configuration>
        <targetClasses>
            <param>com.xxx.order.mapper.*</param>
        </targetClasses>
        <targetTests>
            <param>com.xxx.order.mapper.*Test</param>
        </targetTests>
        <excludedClasses>
            <param>com.xxx.order.entity.*</param>
        </excludedClasses>
        <mutators>
            <mutator>DEFAULTS</mutator>
            <mutator>EXPERIMENTAL_RETURN_VALS</mutator>
            <!-- 自定义 SQL 变异,需先实现 SqlMutatorInterceptor -->
            <mutator>SQL_CONDITIONALS_BOUNDARY</mutator>
        </mutators>
        <outputFormats>
            <outputFormat>HTML</outputFormat>
            <outputFormat>XML</outputFormat>
        </outputFormats>
        <threads>4</threads>
        <timestampedReports>false</timestampedReports>
        <withHistory>true</withHistory>
        <verbose>true</verbose>
    </configuration>
    <executions>
        <execution>
            <id>mutation-test</id>
            <phase>test</phase>
            <goals>
                <goal>mutationCoverage</goal>
            </goals>
        </execution>
    </executions>
</plugin>
  1. Spring Boot 测试基类:启动嵌入式 H2,并填充初始数据
@SpringBootTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@MybatisTest
@Sql(scripts = {"classpath:db/schema-h2.sql", "classpath:db/data-h2.sql"})
public abstract class MapperTestBase {
    @DynamicPropertySource
    static void props(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", () -> "jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
        registry.add("spring.datasource.driver-class-name", () -> "org.h2.Driver");
    }
}
  1. 编写针对 Mapper 的“强”测试用例
class OrderMapperTest extends MapperTestBase {
    @Autowired
    private OrderMapper orderMapper;

    @Test
    void shouldReturnEmptyWhenStatusNotMatched() {
        List<Order> list = orderMapper.selectByStatus(99); // 不存在的状态
        assertThat(list).isEmpty();   // 能杀死 ROR 变异(≥ 改为 >)
    }

    @Test
    void shouldReturnCorrectWhenIdExactMatch() {
        Order o = orderMapper.selectByPrimaryKey(1L);
        assertThat(o.getAmount()).isEqualByComparingTo("100.00"); // 能杀死 AOR 变异(amount+1)
    }
}
  1. 运行命令
mvn clean test pitest:mutationCoverage -DwithHistory

期望结果:Mapper 接口变异覆盖率 ≥ 90%,杀死率 ≥ 85%,报告位于 target/pit-reports/index.html,CI 门禁配置 pitest.mutationThreshold=85,低于阈值直接拒绝合并。

拓展思考

  1. MyBatis 注解模式如何变异?
    注解 SQL 在 MappedStatement 的 SqlSource 里是 ProviderSqlSource,可自定义 ProviderMutator 对 @SelectProvider 的字符串做文本级变异,思路与 XML 相同,但需额外解析 SpEL 占位符。

  2. 二级缓存场景下变异是否有效?
    开启二级缓存后,相同 SQL 第二次走缓存,变异体不会被触发,必须在测试类上加 @DirtiesContext 或手动 sqlSession.clearCache(),否则杀死率虚高,面试官会质疑数据真实性。

  3. 分库分表中间件(ShardingSphere)如何兼容?
    中间件会重写 SQL,PIT 变异后的 SQL 可能被改写失败,解决策略:

    • 在 pitest 配置里排除 ShardingDataSource 相关类;
    • 使用 H2 单库模式跑变异,逻辑表与物理表 1:1 映射,保证变异算子生效。
  4. 增量变异与代码评审结合:
    在 GitLab MR 页面嵌入 pitest-git 报告链接,红色变异体对应行直接标注在 diff 上,评审人点“必须全部杀死”才能合并,这套流程在蚂蚁、字节已落地,面试时可作为“工程化亮点”抛出。