SpringBoot Getting Started Tutorial 02-How to use spring-boot-starter-test gracefully for unit testing

SpringBoot Getting Started Tutorial 02-How to use spring-boot-starter-test gracefully for unit testing

Preface

I have read some springboot tutorial blogs, most of the tutorials on unit testing here are relatively old, and some blogs even let exclusions drop the package under spring-boot-starter-test, and then re-introduced junit4 for unit testing.

The author thinks that these methods are not bad, but they are not elegant enough. Let’s talk about how to use the built-in spring-boot-starter-test for unit testing gracefully.

Environmental description

  • We use the tutorial section 1 of the project to build a portal
  • springboot version number 2.3.1.RELEASE
  • The pom file is generated when the project is built directly using Spring Assistant, and no line needs to be changed

The first test case

Open the test/java directory, we found that the intimate Spring Assistant has helped us build the first test case-SpringbootDemoApplicationTests

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootDemoApplicationTests {
    
    

	@Test
	void contextLoads() {
    
    
	}

}

If you are developing an idea tool, there will be a triangle symbol on the leftmost side of the contextLoads() method line, click to run the test method.

After running, we can see the console output a bunch of unintelligible logs, and then prompt "Tests passed"

At this time you must have the following 2 questions

  • What exactly does the @SpringBootTest annotation do
  • Why is the method of the built-in test case called contextLoads

What exactly does the @SpringBootTest annotation do

We make a transformation to the first test case, the code is as follows:

@Test
void contextLoads(ApplicationContext ctx) {
    
    
    System.out.println("Let's inspect the beans provided by Spring Boot:");
    String[] beanNames = ctx.getBeanDefinitionNames();
    System.out.println(String.format("Spring applicationtext has %d beans total !", beanNames.length));
    Arrays.sort(beanNames);
    for (String beanName : beanNames) {
    
    
        System.out.println(beanName);
    }
}

The running log is as follows:

Let's inspect the beans provided by Spring Boot:
Spring applicationtext has 125 beans total !
applicationAvailability
applicationTaskExecutor
basicErrorController
beanNameHandlerMapping
beanNameViewResolver
characterEncodingFilter
...

We can find that there are a total of 125 beans in the spring container, and our custom helloController is also in it. So the 2 small questions in the previous chapter are easy to answer

  • The @SpringBootTest annotation will simulate SpringBoot application startup, create an ApplicationContext container, and inject built-in beans and user-developed beans into the ApplicationContext container.
  • The above process can be called the process of container loading, so the method is named contextLoads

Since our custom helloController is also in the spring container, how do we call it?

Call the custom Controller in the SpringBoot application

Create a new controller package under the com.henry package of src/test/java, and then create a new HelloControllerTest class, the code is as follows:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerTest {
    
    
    @LocalServerPort
    private int port;

    private String baseUrl;
    private TestRestTemplate restTemplate;

    @BeforeEach
    public void setUp(){
    
    
        this.baseUrl="http://127.0.0.1:"+port;
        this.restTemplate = new TestRestTemplate();
    }

    @Test
    public void index() {
    
    
        System.out.println("request url is: "+baseUrl);
        ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
        System.out.println(response.getBody());
        Assertions.assertEquals(response.getBody(),"Welcome to Spring Boot!");
    }
}    

Run the index method, you can see that you can successfully call the helloController in the springboot application

Below we have an explanation of several parameters

  • webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT //Specify a random port to start the built-in web application server
  • @LocalServerPort This annotation will assign the startup port of the springboot built-in web application server to its annotated field, which is the port field
  • @BeforeEach junit5 adds a new annotation, which is equivalent to the @Before annotation before junit4, and will be executed before the @Test annotation

If webEnvironment does not specify attributes, the @SpringBootTest annotation will only initialize the spring container and inject beans, but will not start the built-in web application server. Specifying RANDOM_PORT is a random port. The advantage of a random port is that it can be played when the application is started. Specifying DEFINED_PORT is the port configured in the configuration file. The default is 8080. If the application is running, the port conflicts when running the test case.

Post the WebEnvironment source code, everyone will know at a glance

public static enum WebEnvironment {
    
    
        MOCK(false),
        RANDOM_PORT(true),
        DEFINED_PORT(true),
        NONE(false);

        private final boolean embedded;

        private WebEnvironment(boolean embedded) {
    
    
            this.embedded = embedded;
        }

        public boolean isEmbedded() {
    
    
            return this.embedded;
        }
    }

Guess you like

Origin blog.csdn.net/l229568441/article/details/106910323