Mockito + JUnit unit test example

Preface

In daily Java development, unit testing is generally required, andMockTesting is one of the important methods in unit testing. so-calledMockTesting refers to a testing method that uses a virtual object to represent some more complex objects that are not easy to construct or obtain during the testing process to facilitate testing. Among them, this virtual object is calledMockObject, the most common way is to use it to representServletmiddleHttpServletRequestobject,JDBCneutralResultSetObjects etc.

by usingMock, we can reduce the coupling of unit tests. If the code has dependencies on other classes or interfaces, throughMockIt can help us simulate these dependencies and help us verify the called dependency behavior. by usingMock, we can verify the calling status of certain methods of the object, how many times it has been called, and what the parameters of the method are.

We have introduced Junit-related knowledge points before. Friends who are not familiar with it can read my previous article ->It’s time to embrace JUnit unit testing!. But one problem when using JUnit is that for complex objects that are difficult to construct, we may need to work hard to solve them. At this point, we can useMockTesting and JUnit combined.

in numerousMockin the frame,MockitoIt is a relatively popular framework, and people often use it in combination with JUnit.Mockitoallows us to create and configureMockObject, thereby simplifying the development of externally dependent test classes to the greatest extent.

Usually, useMockitoIt can be divided into the following three steps:

  1. First, mock and replace external dependencies in the test code.
  2. Second, execute the test code.
  3. Finally, verify that the test code is executed correctly.

Let’s see how to use itMockito + JUnit。

Create project and add dependencies

Since you want to test, you must write code. In order to facilitate dependency management, a Maven project is created as an example. If you still don’t know how to create a Maven project, it is recommended to read the following article first.

Maven Getting Started: Using IDEA to Create Maven Projects | JavaPark

After creating the project, the project structure is as shown in the figure below.

Immediately afterwards, we reported to the projectpom.xmlAdd inMockitoandJUnitdependence.

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>4.3.1</version>
        <scope>test</scope>
    </dependency>
</dependencies>

finally gotpom.xmlThe contents of the file are as follows:

<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">
        <modelVersion>4.0.0</modelVersion>
    <groupId>site.cunyu1943</groupId>
    <artifactId>mockito-junit-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>mockito-junit-demo Tapestry 5 Application</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.8.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>4.3.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Write code and test

After creating the project and adding relevant dependencies, we can write code and continue testing.

Similarly, first we add a simpleDemoclass and declare a method in it, the final code of which is as follows.

public class Demo {
    public int sum(int start, int end) {
        int sum = 0;
        for (int i = start; i <= end ; i++) {
            sum += i;
        }
        return sum;
    }
}

Then inDemoRight-click the class and selectGenerate, the following options will pop up, we chooseTestTo automatically generate test code for this class.

chooseTestAfterwards, IDEA will not generate the corresponding test class immediately, but will pop up the following configuration window for us to configure before generating. The main points to note here are:

  1. Testing library: Class library used for testing, we generally choose it for testingJUint4orJUnit5
  2. Class name: The class name of the test class. The default here is generallyClass name + Test, which can be modified according to your own needs.
  3. Destination package: The package where the generated test class is located, generally corresponds to the package where the above class is located.
  4. Generate test methods for: Here is mainly to select the method that needs to generate tests, as shown belowMemberJust select it.

After the configuration is completed, IDEA willtest/javaPackages are automatically created in the folder and corresponding test classes are generated. The final automatically generated test classes are as follows.

Finally, we followMockThe three steps of testing are used to write code, and the final testing method is as follows.

class DemoTest {
    @Test
    void sum() {
        Demo demo = Mockito.mock(Demo.class);
        Mockito.when(demo.sum(1, 10)).thenReturn(55);
        Assertions.assertEquals(55, demo.sum(1, 10), "The results are not as expected");
    }
}

in,@TestyesJUnitAnnotations in are used to identify test methods.

Then line 4 in the above code corresponds to the first step in the test, simulating external dependencies and creatingDemoObject.

Line 5 corresponds to the second step in the test, executing the test code and then returning the execution results.

Line 6 corresponds to the third step in the test, verifying whether the code is executed correctly. The main ones used here areMockitoassertion method in .

Finally, execute the method in the test class. If the test passes, the following results will appear in IDEA.

Suppose we modify the expected value in the assertion in the above code, the test will not pass, and IDEA will return the prompt information in the assertion.

class DemoTest {
    @Test
    void sum() {
        Demo demo = Mockito.mock(Demo.class);
        Mockito.when(demo.sum(1, 10)).thenReturn(55);
        Assertions.assertEquals(56, demo.sum(1, 10), "The result is not as expected");
    }
}

Summarize

The above content is aboutMockitomatchJUnitHere is a simple example of unit testing, mainly from two aspects. On the one hand, it is how to create and add corresponding dependencies; on the other hand, it is how to write code and automatically generate corresponding test classes, and then write test code. And more aboutMockitoWe will introduce the usage techniques in another article.

Related Posts

The detailed process of SpringBoot integrating Alibaba Cloud SMS service (guaranteed that beginners can also implement it)

“New Semester, New FLAG” Breaking the Limit

Detailed explanation of the use of Java’s jmap command

[WebSocket] Protocol Detailed Explanation

Docker, which has 54k stars on Github, what exactly is it?

Java Date time zone settings (GMT and CST)

ES ElasticSearch Connection reset by peer problem solving

Mockito detailed tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*