All Products
Search
Document Center

AI Coding Assistant Lingma:Best practice for unit testing

Last Updated:Jun 06, 2025

Lear about how to write effective unit tests using Lingma.

What is unit testing?

Unit testing is a software testing method where developers write code to verify the correctness of the smallest testable units of an application, such as functions, methods, or classes. Developers write unit tests during or after feature implementation to ensure each unit works as expected by the design.

Value of unit testing

The value of unit testing is primarily reflected in improved software quality and reliability, ensuring that code continues to function properly after modifications or refactoring. The advantages of unit testing include the following:

  • Improved code quality: Discovers errors and vulnerabilities in the code, thereby improving code quality and reliability.

  • Increased development efficiency: Identifies issues promptly during development, reducing development cycles and costs.

  • Easier refactoring and maintenance: Ensures that code does not introduce new errors and vulnerabilities during refactoring and maintenance.

  • Enhanced team collaboration: Serves as a communication and collaboration tool among team members, improving team collaboration efficiency and quality.

Additionally, unit testing allows you to detect software failures at the earliest opportunity. This prevents losses caused by the difficulty of identifying and repairing bugs later. The regression feasibility of unit testing provides security protection for software and subsequent refactoring. Unit testing also provides instructions and sample code to demonstrate how to use software units.

Principles to follow

Adequate unit testing is imperceptive like air and must ensure software testing quality. From a macro perspective, adequate unit testing must be automatic (A), independent (I), and repeatable (R).

  • A: Automatic: Unit tests should be automatically executed to quickly confirm that newly added code does not break existing functionality when code changes. Typically, unit tests are integrated into continuous integration, automatically triggering unit tests whenever code changes.

  • I: Independent: Each unit test should be independent and not rely on the execution order or results of other tests. To ensure the independence of a unit test, the smallest testable unit of an application must be tested.

  • R: Repeatable: Good unit tests should yield the same results under the same conditions each time they are run. The test cannot depend on external factors, such as networks, databases, or file systems. These external dependencies must be correctly mocked.

Additionally, good unit tests must also have clear assertions, fast execution, thorough boundary testing, and high coverage. Unit tests that follow these principles are qualified and are a crucial part of code quality assurance.

Write a unit test

This section describes how to write a unit test in Java.

Break down detailed test cases

Consider branches

When you write a unit test, you must consider all branches in your code. Branches include the IF, IF ELSE, and SWITCH statements. Each branch must be separately tested. For example:

public String classifyNumber(int number) {
    if (number < 0) {
        return "negative";
    } else if (number == 0) {
        return "zero";
    } else {
        return "positive";
    }
}

In the preceding code, the following branches must be tested:

  • number < 0.

  • number == 0.

  • number > 0.

You must write a test case for each branch.

Find boundary conditions

In addition to branches, you must consider boundary conditions. For example, for the preceding classification functions, the boundary values are -1, 0, and 1. Boundary condition testing can identify potential issues and ensure that the code can work properly under extreme conditions.

Establish unified test standards

Naming conventions

A unit test class is named in the following format: Class name + Test. For example, if you want to test a Calculator class, the unit test class is named CalculatorTest. The name of a unit test method must describe the specific content to be tested. For example:

public class CalculatorTest {
    @Test
    public void testAddition() {
        // The content to be tested.
    }
    @Test
    public void testSubtraction() {
        // The content to be tested.
    }
}

Storage path

In general, a unit test class is stored under the same package name as the class to be tested but in a different directory. For example, in the standard structure of a Maven project, the source code is stored in the src/main/java directory, and the unit test code is stored in the src/test/java directory.

src/main/java/com/example/Calculator.java
src/test/java/com/example/CalculatorTest.java

Choose the right testing framework

JUnit and Mockito are common unit testing frameworks in Java. This section describes how to use these two frameworks to write a basic unit test:

Junit

JUnit is the most famous unit testing framework in Java. It is concise and easy to use and provides extensive annotations and assertions.

  1. Add JUnit as a dependency. In this example, a Maven dependency is used.

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
  2. Write a unit test:

    import org.junit.Test;
    import static org.junit.Assert.*;
    
    public class CalculatorTest {
        @Test
        public void testAddition() {
            Calculator calculator = new Calculator();
            assertEquals(5, calculator.add(2, 3));
        }
    }

Mockito

Mockito is a powerful mocking framework that allows you to create mock objects and simplify unit testing, especially when testing dependencies are not easy to create.

  1. Add Mockito as a dependency:

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>3.11.2</version>
      <scope>test</scope>
    </dependency>
  2. Write a unit test:

    import static org.mockito.Mockito.*;
    import org.junit.Test;
    
    public class UserServiceTest {
        @Test
        public void testGetUser() {
            UserService userService = new UserService();
            UserRepository mockRepo = mock(UserRepository.class);
    
            when(mockRepo.findUserById(1)).thenReturn(new User(1, "John Doe"));
            userService.setUserRepository(mockRepo);
    
            User user = userService.getUserById(1);
            assertNotNull(user);
            assertEquals("John Doe", user.getName());
        }
    }

How to quickly generate unit tests with Lingma

Most developers adopt test-later development based on their programming habits. This means they write code first and then write unit tests later for the code. In this context, using Lingma to generate unit tests is particularly convenient. The following section describes several ways to generate unit tests using Lingma.

Generate a unit test by selecting code

In the IDE editor, select a piece of code and use /unittest to generate a unit test corresponding to the selected code.

整屏示例@1x (5)

Note

When using the /unit test command, add context in the chat box to generate test cases that better meet the developer's needs. For example, if you need to support JUnit5 or use Mockito for mocking, you can use /unit test JUnit5 Mockito. The two keywords after the command are parameters for the preceding command. This method also applies to other commands.

Generate a unit test using shortcut buttons

Click the Lingma icon above each method signature, and select the UnitTest in the drop-down menu.

image

You can also select a code block to generate a unit test. Right-click the selected code block, and choose Lingma > Unit Test.

image

Apply the unit test

After the unit test code is generated, three icons are available in the upper-right corner of the code block in the AI Chat panel:

  • Insert Code: allows you to insert the generated unit test code into the currently opened file.

  • Copy: allows you to copy the generated unit test code in the code block and select the file to which you want to paste the code.

  • Create File: allows you to generate a unit test class file based on the principles of unit testing in Java in the test directory in which unit test methods are stored. If a unit test class file with the same name already exists, you must determine whether to overwrite the existing file.

image

Ask questions on the generated unit test

If you are not satisfied with the generated unit test code, or if you need to use a specific unit test framework or generate more unit test methods, enter your questions in the chat box or click the preset unit test question tags, such as Retry, Use Mockito, Use Spring Test, and Explain code, to ask more questions until you are satisfied with the generated unit test code.

image

Note

In most cases, Lingma will generate common test cases but won't cover all possible scenarios. If you consider that the generated test cases are insufficient, it's recommend to: 1. First accept the generated test cases and add them to your test file. 2. Then switch to the test file and use code completion feature. Lingma will help you continue writing new test cases.

Summary

Unit testing is an essential programming practice for ensuring code quality. The test-first approach in test-driven development (TDD) significantly promotes better code design through iteration. Lingma can help by reducing the workload of setting up unit testing frameworks and writing test cases, while keeping test cases current by suggesting additional test scenarios and adapting tests to code changes.