How to replace @Rule annotation in Junit 5?

你离开我真会死。 提交于 2020-01-24 02:01:06

问题


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 no suggestions when I'm trying to import @Rule annotation. Do I need to add another module of junit dependency? Or rules are not supported in Junit5? If not how can I replace @Rule annotation to make tests work again? Thanks.


回答1:


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 Extensions as required may be added for a test class.

To handle the issue you have several possible approaches among :

  • keep the JUnit 4 way (JUnit 5 owns the JUnit Vintage part that allows to execute JUnit 3 or 4 tests).
  • rewrite the @Rule as an Extension.
  • do the actual processing done by WireMockRule (start the server, execute your tests and stop the server) in each test of class with @BeforeEach and @AfterEach hook methods.
  • use a third library that implements the equivalent of WireMockRule in the JUnit 5 Extension way such as https://github.com/lanwen/wiremock-junit5

Note that your issue already discussed in the JUnit 5 Issues.




回答2:


JUnit 4 annotations @Rule and @ClassRule do not exist in JUnit 5. Basically there is a new extension model that can be used to implement extensions with the same functionality. These extensions can be used with the @ExtendWith annotation.

There is a limited migration support for a subset of JUnit 4 rules in the junit-jupiter-migrationsupport module. Unfortunately, it's only limited to subclasses of ExternalResource and Verifier.

Before wiremock has official support for JUnit you have some workarounds:

  1. Run JUnit 4 tests side by side with JUnit 5 tests with the junit-vintage-engine.
  2. Start and stop the server yourself in the test code.
  3. Use a 3rd party extension like wiremock-junit5 or wiremock-extension.


来源:https://stackoverflow.com/questions/51012335/how-to-replace-rule-annotation-in-junit-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!