I'm using WireMock in my tests and have such a line of code:
@Rule public WireMockRule wireMockRule = new WireMockRule(8080);
I want to switch to JUnit 5. So I added the next dependency (using Gradle):
testCompile('org.junit.jupiter:junit-jupiter-engine:5.1.1')
But there are no suggestions when I'm trying to import @Rule
annotation.
Do I need to add another module of JUnit dependency? Or are rules not supported in JUnit 5? If not, how can I replace @Rule
annotation to make tests work again?
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.
@ExtendWith is a repeatable annotation that is used to register extensions for the annotated test class, test interface, test method, parameter, or field. Annotated parameters are supported in test class constructors, in test methods, and in @BeforeAll , @AfterAll , @BeforeEach , and @AfterEach lifecycle methods.
JUnit Vintage ensures that existing JUnit tests can run alongside newer tests created using JUnit Jupiter. JUnit 5's architecture also supports running multiple test engines simultaneously: you can run the JUnit Vintage test engine with virtually any other test engine that is compatible with JUnit 5.
JUnit 5 extensions are related to a certain event in the execution of a test, referred to as an extension point. When a certain life cycle phase is reached, the JUnit engine calls registered extensions. Five main types of extension points can be used: test instance post-processing. conditional test execution.
In a general way, what you did with @Rule
and @ClassRule
in JUnit 4 should be done with @ExtendWith
and Extension
that associated provide a very close feature in JUnit 5.
It works as standards JUnit lifecycle hooks but that it is extracted in a Extension
class. And similarly to @Rule
, as many Extension
s as required may be added for a test class.
To handle the issue you have several possible approaches among :
@Rule
as an Extension
.WireMockRule
(start the server, execute your tests and stop the server) in each test of class with @BeforeEach
and @AfterEach
hook methods.Note that your issue already discussed in the JUnit 5 Issues.
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