My micro-service project based on spring-boot framework and all my unit test running with spring runner.
@RunWith(SpringRunner.class)
adding this annotations, imports the following library:
import org.springframework.test.context.junit4.SpringRunner;
How can I set my test classes to run with junit5 ?
Please note that JUnit 5 is not backward compatible with JUnit 4, but the JUnit team created the JUnit Vintage Project to support JUnit 4 test cases on top of JUnit 5.
In JUnit 4, we used the @Rule and @ClassRule annotations to add special functionality to tests. In JUnit 5. we can reproduce the same logic using the @ExtendWith annotation.
There is no difference, from the javadoc: SpringRunner is an alias for the SpringJUnit4ClassRunner.
Automatically Migrate All Tests Use Find Action with ⌘⇧A, or Ctrl+Shift+A, and type Migrate, to see migration options for the code. IntelliJ IDEA offers the option to migrate the code from JUnit4 to JUnit5. This migration is similar to what we did with the individual test class, but for all test classes.
Remove JUnit4 from your build Path.
For example :
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@TestPropertySource(locations = "classpath:application-local.properties")
public class MyTest {
@Before
public void setUp() {
...
}
@Test
public void testMethod() {
Assert.assertTrue(...);
}
}
will become
@SpringBootTest(classes = Application.class)
@TestPropertySource(locations = "classpath:application-local.properties")
public class MyTest {
@BeforeEach
public void setUp() {
...
}
@Test
public void testMethod() {
Assertions.assertTrue(...);
}
}
Using JUnit Jupiter (aka JUnit 5) no longer requires ˋ @RunWith(SpringRunner.class)ˋ since this is a JUnit 4 mechanism. With recent versions of Spring/Spring Boot JUnit 5 support comes out of the box eg through using ˋspring-boot-starter-testˋ.
I recommend to exclude dependencies on JUnit 4 in your Maven/Gradle file to make confusing JUnit 4 and 5 features less likely.
Here’s an article that shows the basics: https://howtodoinjava.com/spring-boot2/testing/junit5-with-spring-boot2/
Spring 2.4 seems to include JUnit 5 and make it the default out of the box.
Besides updating @RunWith(SpringJUnit4ClassRunner.class)
to @ExtendWith(SpringExtension.class)
I had to add the following to build.gradle
for the tests to actually run:
test {
useJUnitPlatform {}
}
This last step may have been due to JUnit 4 being a dependency of one of my dependencies, but every other thing I read didn't suggest this was needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With