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.

Recommended Today

Libp2p RS version 0.3.0 introduction

V0.3.0 released on 4.23, usingAsyncRead & AsyncWriteTo replace ourReadEx & WriteEx & SplitEx; SimplifiedKad/DHTImplementation logic. modify ReadEx & WriteEx & SplitEx: At first we tried to useasync-traitTo define their own IO operationsTraitFor more pure useasync/awaitTo write code. withReadExFor example, it is roughly as follows: #[async_trait] pub trait ReadEx { async fn read(&mut self, buf: &mut […]