Junit 5 test in springboot application, first try
After using springboot for several years, I admit that I am still keep using junit 4 not 5.
Today I want to do something a litttle differently, So I decide to write all new unit tests in junit 5.
Springboot reference guide makes it very clear, in section 4.25 Testing, they said:
The starter also brings the vintage engine so that you can run both JUnit 4 and JUnit 5 tests. If you have migrated your tests to JUnit 5, you should exclude JUnit 4 support, as shown in the following example:
Well, this is not what I like to do because there're a lot of junit 4 unit tests out there, so I just upgrade springboot version in my pom file from 2.1.5 to 2.2.6. The reason for doing this comes from the reference guide to:
The spring-boot-starter-test “Starter” (in the test scope) contains the following provided libraries: JUnit 5 (including the vintage engine for backward compatibility with JUnit 4): The de-facto standard for unit testing Java applications.
For junit 4, I always use @RunWith(SpringRunner.class)
, but for junit 5, I change this to :
@SpringJUnitConfig(TaskServiceTest.Config.class)
public class TaskServiceTest {
@Configuration
static class Config {
}
Then add a plain stupid test case and a setUp method:
@BeforeEach
public void setUp() {
System.out.println("Hello World");
}
@Test
public void testHelloWorld() {
assertTrue("hello".equalsIgnoreCase("HeLLo"));
}
Run test ... good, all green. But wait, why the string "Hello World" is not printed out ?
This drives me crazy, like anyone will do, I do a lot of googling but have no luck. A post in 2018 even said it happens for missing maven surefire plugin in pom file.
Finally I find the cause (a really stupid one): I import a wrong class. Instead of org.junit.Test, I should import org.junit.jupiter.api.Test. After change to that class, everything runs fine.