SuperAPI AI Directory

backend-unit-test

Testing & quality

View repository

Updated 10-16 05:06

About this skill

Backend Unit Testing Skill

Execution Flow (Two Steps)

# 步骤1: 编译测试类
cd sfm_back && mvn compiler:testCompile -pl <module> -am

# 步骤2: 运行测试
cd sfm_back && mvn surefire:test -pl <module> -am -Dtest="测试类名"

Parameter Description

Parameter Purpose
-pl <module> Specify the module, such as med-ams、med-bpm-biz
-am Also build dependent modules (reactor mode), without going through install
-Dtest="xxx" Specify the test class, supports wildcard *

Examples

# 编译 + 运行 med-ams 模块测试
cd sfm_back && mvn compiler:testCompile -pl med-ams -am
cd sfm_back && mvn surefire:test -pl med-ams -am -Dtest="AmsPropertyReadServiceTest"

# 使用通配符运行多个测试
cd sfm_back && mvn surefire:test -pl med-ams -am -Dtest="AmsPropertyReadService*"

# 运行所有测试
cd sfm_back && mvn surefire:test -pl med-ams -am -Dtest="*Test"

Create Test Files

<module>/src/test/
├── java/com/jp/med/<module>/modules/<功能>/<ServiceTest>.java
└── resources/application.yml
package com.jp.med.<module>.modules.<功能>;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;

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

@SpringBootTest
@ActiveProfiles("unit-test")
@Transactional
class <ServiceTest> {

    @Autowired(required = false)
    private <Service> targetService;

    @Test
    void contextLoads() {
        assertNotNull(targetService, "服务应该被注入");
    }
}
# src/test/resources/application.yml
spring:
  main:
    lazy-initialization: true
    banner-mode: off

Database

  • Local:jdbc:postgresql://localhost:5432/jp_db_20260305
  • The test uses the actual database connection configured in Nacos
  • @Transactional Ensure test data automatically rolls back

Common Issues

Issue Cause Solution
No tests executed Test class not compiled First compiler:testCompile
Compilation failed import error Check whether the package path matches the directory
med-common dependency error Resources are cleaned after clean Avoid clean; compile directly
Test run: 0 Test class name does not match Confirm the class name or use wildcard *

Notes

  • ❌ Do not modify any pom.xml
  • ❌ Do not execute mvn install
  • ❌ Avoid mvn clean(triggers resource filtering issues)
  • ✅ Always use -am parameter to ensure dependencies are built correctly
  • ✅ Compile first, then run; two steps

Workflow

  1. Check existing tests:find sfm_back -path "*/test/*" -name "*Test.java"
  2. Create test files(if needed)
  3. Compile:mvn compiler:testCompile -pl <module> -am
  4. Run:mvn surefire:test -pl <module> -am -Dtest="TestName"
  5. Verify:Tests run: X, Failures: 0, Errors: 0