×
Community Blog Best Practices for Generating a Unit Test by Using Tongyi Lingma to Simplify Unit Testing

Best Practices for Generating a Unit Test by Using Tongyi Lingma to Simplify Unit Testing

This article discusses what unit testing is, the value of unit testing, the principles of adequate unit testing, and how to write an adequate unit test.

By Huzai

1. What Is Unit Testing?

Unit testing is a method of software testing where code is written to verify the correctness of the smallest testable unit of an application, such as a function, method, or class. Developers write unit tests during or after feature implementation to ensure that each smallest testable unit is working as expected by the design.

2. Value of Unit Testing

The value of unit testing mainly lies in the improvement of the quality and reliability of software to ensure that the code can still run after modification or refactoring. Unit testing has the following benefits:

Enhances code quality: Unit testing helps you find bugs and vulnerabilities in your code to improve the quality and reliability of the code. ‌

Increases development efficiency: Unit testing helps you identify issues in the development process in time to reduce the development cycle and costs. ‌

Simplifies refactoring and maintenance: Unit testing helps you eliminate errors and vulnerabilities during code refactoring and maintenance. ‌

Fosters team collaboration: Unit testing boosts the efficiency and quality of team collaboration as a communication and collaboration tool for team members. ‌

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

3. Principles

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

Automatic (A): An adequate unit test must be automatically run. This way, you can quickly confirm that code changes do not destroy existing features. In most cases, unit testing is applied in continuous integration environments, in which a unit test can be automatically triggered by code changes.

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

Repeatable (R): An adequate unit test must give the same results every time it is run under the same conditions. The test cannot depend on external factors, such as networks, databases, or file systems. These external dependencies must be correctly mocked.

In addition, an adequate unit test must be characterized by clear assertions, short duration, sufficient boundary testing, and high coverage. Unit tests that follow these principles are qualified and are a crucial part of code quality assurance.

4. Write a Unit Test

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

4.1 Split a Unit Test into 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. Sample code:

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 three branches must be tested:

• number < 0
• number == 0
• number > 0

For each branch, you must write a test case.

Find Boundary Conditions

In addition to branches, you must also 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.

4.2 Establish Unified Unit Testing Specifications

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. Sample code:

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

4.3 Use an Appropriate Unit 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.

Step 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>

Step 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.

Step 1: Add Mockito as a dependency.

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>3.11.2</version>
  <scope>test</scope>
</dependency>

Step 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());
    }
}

5. Quickly Generate a Unit Test by Using Tongyi Lingma

Most developers adopt test-later development to perform unit testing based on their programming habits, which means that they write code first and then write unit tests for the code. In this case, it is particularly convenient to generate unit tests by using Tongyi Lingma. This section describes several methods of generating unit tests by using Tongyi Lingma.

5.1 Generate a Unit Test by Selecting Code

In the WebIDE of Tongyi Lingma, select a code block in the code editor. In the conversational search section, run the /generate unit test command to generate a unit test for the code that you selected.

1

Note: When you run the /generate unit test command, you can add more information in the field to generate test cases that meet your business requirements. If you need to use JUnit 5 or Mockito, you can enter /generate unit test JUnit5 Mockito. In this case, the two keywords are used as the parameters of the command. This method is also applicable to other commands.

5.2 Generate a Unit Test by Using Shortcut Buttons

The plug-in of Tongyi Lingma displays a small icon above each method signature. Select Generate Unit Test from the drop-down menu that appears after you click the icon.

2

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

3

5.3 Apply the Generated Unit Test

After the unit test code is generated, three icons are available in the upper-right corner of the code block in the conversational search section:

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.

4

5.4 Ask Questions on the Generated Unit Test

If you are not satisfied with the generated unit test code because you need to use a specific unit testing framework or require more unit test methods, you can enter questions in the field in the conversational search section. You can also click the preset tags to ask questions on the generated unit test code, such as Retry, Use Mockito, Use Spring Test, and Explain code, until you are content with the unit test code generated by Tongyi Lingma.

5

Note: Unit tests generated based on code generally enumerate commonly used test cases and do not traverse all test cases. If you consider that the generated test cases are insufficient, we recommend that you apply the generated test cases to the test file first. Then, switch to the test file and use Tongyi Lingma to continue writing subsequent code and creating more test cases.

6. Conclusion

Unit testing is an important programming practice that ensures code quality during the coding process. At the same time, the use of test-first in test-driven development can significantly promote the evolution of code design. To a large extent, Tongyi Lingma can reduce the workload of building unit testing frameworks and writing test cases. Tongyi Lingma can also maintain the effectiveness and usability of unit test cases to notably improve the quality of coding.

1 1 0
Share on

You may also like

Comments

5251276510954725 January 2, 2025 at 9:03 am

nice