Boost Java Repository Testing with AI: How Aone Copilot Agent Generates Unit Tests

This article details how the Aone Copilot Agent, guided by carefully crafted prompts, automates unit test creation and code modifications for a Java Spring Boot GoodsDomainRepository, achieving a 50% code adoption rate and outlining prompt design, test architecture, execution flow, and best‑practice recommendations.

Alibaba Cloud Developer
Alibaba Cloud Developer
Alibaba Cloud Developer
Boost Java Repository Testing with AI: How Aone Copilot Agent Generates Unit Tests
AI testing illustration
AI testing illustration

Overview

Using Aone Copilot Agent and well‑designed prompts, AI can automatically generate unit tests and modify code for the GoodsDomainRepository in a Spring Boot service‑package upgrade project. In practice the AI code adoption rate is about 50%, and improving prompt quality further enhances results.

Project Background and Requirements

Business Background

The project requires complete unit tests for the GoodsDomainRepository, which handles complex business logic and data conversion, making manual test writing inefficient and error‑prone.

Core Requirements

Establish an AI‑assisted mechanism that, based on standardized test templates, automatically produces complete and规范 test case code, improving development efficiency and test quality.

Interface Example

/**
 * 商品仓储接口
 * @author AI
 * @date 2025-01-12
 */
public interface GoodsDomainRepository {
    /** 根据商品ID查询商品信息 */
    GoodsDomain findById(ServiceGoodsIdDomain goodsId);
    /** 批量查询商品信息 */
    List<GoodsDomain> findByIds(List<ServiceGoodsIdDomain> goodsIds);
    /** 查询所有商品 */
    List<GoodsDomain> findAll();
}

Practice Solution Design

AI Prompt Rules Design

Standardized configuration: unified Spring Boot test environment.

Data‑driven verification: prefer database comparison over hard‑coded checks.

Full scenario coverage: normal, exception, boundary, and business cases.

Standardized naming: clear method naming conventions.

Maintainability: clear code structure and sufficient comments.

Test Architecture Template

@SpringBootTest(classes = {TestApplicationConfig.class, TestMybatisConfig.class})
@Import({GoodsDomainRepositoryImpl.class})
@Transactional // ensure test data rollback
@Sql(scripts = "classpath:sql/dml/repo/GoodsDomainRepositoryImplTest.sql")
@RunWith(SpringRunner.class)
public class GoodsDomainRepositoryImplTest {
    // test code
}

Data Validation Strategy

// Query expected data
ServiceGoodsInfoParam param = new ServiceGoodsInfoParam();
param.createCriteria().andGoodsIdEqualTo(goodsId);
List<ServiceGoodsInfoDO> dos = serviceGoodsInfoMapper.selectByParam(param);
ServiceGoodsInfoDO expectedData = dos.get(0);
// Compare with result
assertEquals("商品名称应该与数据库一致", expectedData.getGoodsName(), result.getGoodsName());

Conditional Validation Logic

ServiceGoodsSaleConfigDO config = serviceGoodsSaleConfigMapper.getByGoodsId(goodsId, "prod");
if (config != null) {
    assertNotNull("当数据库中存在售卖配置时,售卖范围不应为空", result.getSaleScope());
    System.out.println("数据库中的售卖配置: " + config.getSaleChannelConfig());
} else {
    System.out.println("数据库中没有找到goodsId=" + goodsId + "的售卖配置");
}

Test Case Design Standards

Method Naming Convention

Format:

test{Method}_{Scenario}_{ExpectedResult}
testFindById_WhenIdNotExists_ShouldReturnNull
testFindById_WhenGoodsIdExists83_ShouldReturnCorrectGoodsDomain
testFindByIds_WhenOneNotExistsOneExists83_ShouldReturnListWithOne

Test Execution Process

Requirement analysis – define test goals and coverage.

Prompt input – provide standardized test rules and specific needs.

Code generation – AI produces test code based on the prompt.

Result verification – run tests and verify generated code quality.

Iterative optimization – refine prompts based on feedback.

Generated Test Example

@Test
public void testFindByIds_WhenOneNotExistsOneExists83_ShouldReturnListWithOne() {
    // Given
    List<ServiceGoodsIdDomain> goodsIds = Arrays.asList(
        ServiceGoodsIdDomain.ofGoods("99999"), // non‑existent ID
        ServiceGoodsIdDomain.ofGoods("83")    // existent ID
    );
    Long existingGoodsId = 83L;
    // When
    List<GoodsDomain> result = goodsDomainRepository.findByIds(goodsIds);
    // Then
    assertNotNull("查找结果不应为空", result);
    assertEquals("应该只返回一个商品", 1, result.size());
    GoodsDomain goodsDomain = result.get(0);
    assertEquals("商品ID应该为83", existingGoodsId.toString(), goodsDomain.getGoodsId().getId());

    // Database verification
    ServiceGoodsInfoParam param = new ServiceGoodsInfoParam();
    param.createCriteria().andGoodsIdEqualTo(existingGoodsId);
    List<ServiceGoodsInfoDO> dos = serviceGoodsInfoMapper.selectByParam(param);
    ServiceGoodsInfoDO expected = dos.get(0);
    assertNotNull("数据库中应该存在goodsId为83的商品信息", expected);
    assertEquals("商品名称应该与数据库一致", expected.getGoodsName(), goodsDomain.getGoodsName());
    assertEquals("服务类型应该为自配送", ServiceType.SELF, goodsDomain.getServiceType());
    // Business rule assertions...
}

Prompt Rule Generation Method

1. Manually write a high‑quality test class as a standard example. 2. Let AI analyze the example and extract common patterns. 3. Standardize the extracted rules into reusable Prompt templates. 4. Validate and iteratively optimize the Prompt.

Core Benefits and Impact

Efficiency: manual test writing reduced from 30 minutes to 5 minutes per method.

Coverage: AI systematically generates diverse scenarios, avoiding omissions.

Quality: standardized structure and clear assertions improve test reliability.

Team empowerment: reusable Prompt rules and tooling accelerate onboarding.

Future Outlook

Further enhancements include higher AI intelligence for automatic business‑rule detection, multi‑level testing support (unit, integration, E2E), AI‑generated test data, and tools for prompt engineering and quality assessment.

Test scenario design illustration
Test scenario design illustration
AI generation result
AI generation result
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaPrompt engineeringSpring BootAI testingunit test generation
Alibaba Cloud Developer
Written by

Alibaba Cloud Developer

Alibaba's official tech channel, featuring all of its technology innovations.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.