SpringBoot unit test introduction practice

preface

There is no doubt about the importance of software testing. Most of the supporting software of the company's main business will require writing tests during development. In daily development, there are many scenarios that require us to write tests. For example, you are going to open source expansion packages, and having a complete test is always a plus 💯.

Environmental projects

  • JDK 14
  • Gradle 6.3
  • macOS 10.15
  • SpringBoot 2.3.4

Introduction to JUnit

Most novices like to use system when testing programs out. Println () method, print the result directly to see if the result meets the expectation. This method is very convenient when testing programs with small amount of code and simple logic. In the actual production project, we can try JUnit tool.

JUnit is the testing framework of Java language. It can verify the correctness of the program according to the Test data, and the Test code is separated from the engineering code. As long as you add the @ Test annotation to the method, JUint can recognize the method.

Introduce dependency

The build tool we use here is gradle, so open build Gradle files introduce dependencies. This dependency includes JUnit and so on, so there is no need to introduce JUnit separately.

implementation 'org.springframework.boot:spring-boot-starter-test:2.3.4.RELEASE'

Test Service layer

Write a DemoService interface, which has only one sayHelloTo method for our simple unit test.

public interface DemoService {
    /**
     * Hello World!
     * @param name name
     * @return String
     */
    String sayHelloTo(String name);
}

Create DemoServiceImpl class and implement DemoService interface. Here you can use ⌥ + ⏎ to quickly create interface implementation classes.

@Service
public class DemoServiceImpl implements DemoService {
    @Override
    public String sayHelloTo(String name) {
        return "say hello to " + name;
    }
}

The unit tests of SpringBoot are written in the src/tests directory. If you are using the IDEA IDE, you can press ⇧ + ⌘ + T to quickly create test files.

@SpringBootTest
class DemoServiceTest {
    @Autowired
    private DemoService demoService;
    @Test
    void sayHelloTo() {
        String result = demoService.sayHelloTo("developer");
        Assertions.assertEquals("say hello to developer", result);
    }
}

The above is the simplest way to write unit tests. Just inject @ SpringBootTest annotation. When you want to execute, place the mouse over the corresponding method and right-click to select run.

Test Controller layer

Write a DemoController, create a sayHelloTo method, and inject the DemoService interface.

@RestController
public class DemoController {
    @Autowired
    private DemoService demoService;

    @GetMapping("demo")
    public String sayHelloTo(String name) {
        return demoService.sayHelloTo(name);
    }
}

Use the ⇧ + ⌘ + T shortcut key to create the Controller test class. Here, MockMvc is used. MockMvc is provided by the spring test package, which realizes the simulation of HTTP requests. It can directly use the form of network and convert to the call of Controller, making the test fast and independent of the network environment. At the same time, a set of verification tools is provided, and the verification of results is very convenient.

@AutoConfigureMockMvc
@SpringBootTest
class DemoControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void sayHelloTo() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/demo?name=developer"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("say hello to developer"))
                .andDo(MockMvcResultHandlers.print());
    }
}

Here, simply use MockMvc to test the HTTP STATUS CODE returned by the API interface and the returned content, and output the whole response result.

summary

Here, I have simply gone through the SpringBoot unit test process, which is only recorded here as an introductory practice. Have a basic understanding of JUnit and MockMvc. Interested partners can query some materials for in-depth study.

Tags: Java

Posted by tomc_1 on Tue, 10 May 2022 08:09:12 +0300