Does SpringBoot need @RunWith when using tests?

When we use SpringBoot for testing, we generally need to add two annotations:

  • @SpringBootTest
    • The purpose is to load the ApplicationContext and start the spring container.
  • @RunWith
    • Is a test starter that can load SpringBoot test annotations
    • Let the tests execute in the Spring container environment. If there is no such annotation in the test class, it will cause the automatic injection of service, dao, etc. to fail

But sometimes when we use it, we find that we can run test classes without @RunWith annotation. I checked a lot of information on the Internet, and many people said that it was the IDEA compiler. Let alone whether what they said was correct, the reason I found was different from them.

I found that the root cause is: @Test import package problem

We actually have two options for importing packages when using @Test:
insert image description here
If we are using the org.junit.jupiter.apiTest annotation under the package, then we don't need the @RunWith annotation.

And if we are using the org.junitTest annotation under the package, then we need the @RunWith annotation. If we don't use it, there will be a null pointer:
insert image description here

This starter can use either SpringJUnit4ClassRunner or SpringRunner.
Actually SpringRunner inherits SpringJUnit4ClassRunner:
insert image description here

Guess you like

Origin blog.csdn.net/zyb18507175502/article/details/128647518