Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude individual test from 'before' method in JUnit

Tags:

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?

like image 331
Tomas Romero Avatar asked Oct 22 '12 18:10

Tomas Romero


People also ask

How do you exclude a test in JUnit?

If you want to ignore a test method, use @Ignore along with @Test annotation. If you want to ignore all the tests of class, use @Ignore annotation at the class level.

What does @after do in JUnit?

org.junit Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception.

What is the tear down () method called in JUnit?

7. When is the tearDown() method called in JUnit? Explanation: The tearDown() method is called after the execution of every @Test method.

What is @before in junit5?

@BeforeEach is used to signal that the annotated method should be executed before each @Test method in the current test class.


1 Answers

You can do this with a TestRule. You mark the test that you want to skip the before with an annotation of some description, and then, in the apply method in the TestRule, you can test for that annotation and do what you want, something like:

public Statement apply(final Statement base, final Description description) {   return new Statement() {     @Override     public void evaluate() throws Throwable {       if (description.getAnnotation(DontRunBefore.class) == null) {         // run the before method here       }        base.evaluate();     }   }; } 
like image 199
Matthew Farwell Avatar answered Oct 13 '22 22:10

Matthew Farwell