Skip to content
Advertisement

Exclude individual test from ‘before’ method in JUnit

All tests in my test class execute a ‘before’ method (annotated with JUnit’s @Before) before the execution of each test.

I need a particular test not to execute this before method.

Is there a way to do it?

Advertisement

Answer

Unfortunately you have to code this logic. JUnit does not have such feature. Generally you have 2 solutions:

  1. Just separate test case to 2 test cases: one that contains tests that require “before” running and second that contains tests that do not require this.
  2. Implement your own test running and annotate your test to use it. Create your own annotation @RequiresBefore and mark tests that need this with this annotation. The test runner will parse the annotation and decide whether to run “before” method or not.

The second solution is clearer. The first is simpler. This is up to you to chose one of them.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement