Pure Junit 5 in maven module

·

0 min read

Mixing junit 4 and junit 5 cause a little confusion, document says:

If you are using JUnit 4, don’t forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there’s no need to add the equivalent @ExtendWith(SpringExtension.class) as @SpringBootTest and the other @…Test annotations are already annotated with it.

So, what will happen if junit 4 and 5 coexist? Should I use @RunWith(SpringRunner.class) or not ? After an experiment of this, I found I still need to use @RunWith annotation in this situation to make things work.

In order to user pure Junit 5 and keep other existed module untouched, I decide to exclude Junit 4 only in one module, so I add the following snippets in a module pom file:

      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
          <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
          </exclusion>
        </exclusions>
      </dependency>

Before doing this, mvn dependency:tree will show:

20200411171642.png

After doing this, Junit 4 (Junit vintage) is gone:

20200411171754.png

Then, I can comment out @RunWith annotation and the tests are still able to be run:

//@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {
  "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc" +
    ".DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa" +
    ".HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.jdbc" +
    ".DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.data" +
    ".jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.amqp" +
    ".RabbitAutoConfiguration"})
public class TaskControllerTest {