Java unit testing and common statements

1 Introduction

Writing Java unit test cases means breaking down a complex code into a series of simple unit test cases, and testing the processing logic in the code in a short time without starting the service. Writing good Java unit test cases is actually to "simplify complex issues and deepen order creation issues." During the writing process, we can also conduct a secondary check on our code.

Here are some of the benefits of writing unit tests that I’ve summarized:

1. When testing code logic, there is no need to start the entire application.

2. Unit tests can cover boundary values

3. Improve the reuse of original code

4. It can effectively avoid the potential impact on the original logic after code changes.

2 Prepare the environment

Mockito is currently the most popular unit testing simulation framework. Mockito can simulate complex objects that an application depends on, thereby isolating test objects from dependent objects. PowerMock provides extended functionality for Mockito. To simulate static methods, final classes, and private methods, etc. We chose to use a framework based on Mockito and supplemented by PowerMock for unit testing.

2.1 Introduce the Mockito and PowerMock packages, and add the following dependencies to the pom.xml file:

<properties>
    <powermock.version>2.0.9</powermock.version>
</properties>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-core</artifactId>
    <version>${powermock.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>${powermock.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>${powermock.version}</version>
    <scope>test</scope>

The latest version of PowerMock is 2.0.9 [ PowerMock link ] Since the PowerMock package already contains the corresponding Mockito and JUnit packages, there is no need to introduce them separately.

3 Some commonly used mock statements

3.1 Simulate object instances of specified classes, used to simulate dependent objects (class members)

In Spring, these member objects are injected through @Autowire, @Resource , @Value, etc., which may involve environment configuration or rely on third-party interfaces. In unit testing, it is not our focus, so we can use mock to simulate

//方法一
Mockito.mock(OrderInfo.class);
//方法二
@Mock
private OrderInfo orderInfo;


@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}

3.2 Define the object to be tested

Instantiate the service class under test

@InjectMocks
private OrderServiceImpl orderService;

3.3 Simulating enumeration types/static methods

The corresponding simulation class needs to be placed in @PrepareForTest

//必须添加@RunWith和@PrepareForTest在类前
@RunWith(PowerMockRunner.class)
@PrepareForTest(OrderTypeEnum.class)


//在@Before中添加枚举mock
@Before
public void beforeTest() {
    mockStatic(OrderTypeEnum.class);
}

3.4 Simulating dependency methods

After simulating the dependent parameters and return values, you can use the Mockito function to simulate the dependent methods. If the mock object also has method calls, you need to mock the methods of these dependent objects.

/***
when.thenReturn 和 doReturn.when是两种实现方式
只有在使用@Spy时才会有区别
参考链接:https://www.imooc.com/wenda/detail/594190#id_653606
***/


//模拟枚举的方法调用
when(OrderTypeEnum.getByValue(anyInt())).thenReturn(100);
//模拟依赖对象的依赖方法调用
doReturn(resultInfoDTO).when(orderInfoService).getLastOrderInfo(orderInfoDTO);

3.5 Simulation construction method

PowerMock provides a simulation of the constructor method, but the class of the constructor method needs to be placed in @PrepareForTest

//必须在@PrepareForTest中添加对应类
@PrepareForTest({OrderTypeEnum.class, OrderServiceImpl.class})
whenNew(OrderInfoDTO.class).withNoArguments().thenReturn(orderInfoDTO);

3.6 Number of verification method calls

After the method under test is called, some methods will be called multiple times or called different times according to different conditions. At this point, the validity of the code can be determined based on the number of verification method calls.

verify(orderInfoService,times(1)).getLastOrderInfo(orderInfoDTO);

3.7 Verify return value

We have certain expectations for the parameters that will be returned after the method is called. Therefore, you can ensure the correctness of the return value by verifying whether the return value meets expectations.

Assert.assertEquals(result, "123");

3.8 Verify exception objects

JUnit's @Test annotation provides an expected attribute, which can specify an expected exception type and is used to catch exceptions and verify their exception types. [Note]: Only the exception type can be verified, but the exception information cannot be verified.

@Test(expected = BPLException.class)

4 Single test examples

The following is a unit test case for a local method that calls an external interface and includes the use of enumeration values.

The source method requires a single test method:

First, there are some necessary initializations for unit testing :

4.1 Single test scenario one (make sure the interface is called and the return value is correct):

Use the verify method to determine whether the interface has been called and only called once.

Use assert to confirm whether the return value meets expectations

4.2 Single test scenario 2 (whether necessary exceptions are thrown):

By adding the expected attribute to the @Test annotation, test whether an exception can be thrown when the interface return value is empty.

4 Summary

Writing unit tests plays an important role in development. During the development process, it is inevitable to optimize or reconstruct historical code. Unit testing can, to a certain extent, help test updated logic and potential call chains. In addition, I also share some links, hoping to help everyone complete the construction from 0 to 1.

5 References

Finally: The complete software testing video tutorial below has been compiled and uploaded. Friends who need it can get it by themselves [guaranteed 100% free]

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are from the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

Guess you like

Origin blog.csdn.net/weixin_50829653/article/details/132609021