Two examples of spring boot unit test

Time:2021-4-16

This article mainly introduces two methods of springboot unit test, and explains the examples in detail. The example code is introduced in great detail, which has a certain reference learning value for everyone’s study or work. If you need a friend, you can refer to it

Spring boot unit test, here are two ways, one is to add comments in the test class; the other is to start the project in the code in the main method of inheritance interface (can also be written in other methods).

For example, unit test the connection pool information of the database

1. Use annotations on classes:

  @RunWith(SpringRunner.class)

  @SpringBootTest


@RunWith(SpringRunner.class)
@SpringBootTest
public class RobotsApplicationTests {

  @Autowired
  DataSource dataSource;

  @Test
  public void test(){
    System.out.println(dataSource.getClass());
  }

}

2. Inherit the commandlinerunner interface

Commandlinerunner: indicates that the function will be executed after the project is started. You only need to write the test content in its run() method, such as:

@SpringBootApplication
@EnableScheduling
@ComponentScan(basePackages={"com.cmit.hall.plat","com.cmit.hall.pub"}) 
@ServletComponentScan(value= {"com.cmit.hall.pub.interceptor","com.cmit.hall.plat.config","com.cmit.hall.pub.session"})
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=1800)
public class PlatApp implements CommandLineRunner {
  
  @Autowired
  DataSource dataSource;

  public static void main(String[] args) {
    SpringApplication.run(PlatApp.class, args);
  }
  
  @Override
  public void run(String... args) throws Exception {
    System.out.println ("> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >;
    System.out.println("DATASOURCE = " + dataSource);
  }
}

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.