How to run the code before each JUnit @Test method separately, without using @RunWith or AOP?

the use case is simple: I want to run some boiler plate code before each method in the JUnit test annotated with @Test and my custom annotation (let her call @Mine).

I do not want to use the following methods (explanation in parentheses):

  • @RunWith (my test may or may not use this annotation already, so I can’t assume that I can use my own runner)
  • AOP (I can’t install dependencies on third-party libraries like AspectJ)

I guess that only leaves me with a reflection, and that’s fine. I tried using @Before and getting the current method via Thread.getCurrentThread (), etc., but for some reason I find this solution a bit dirty, since I will have to make the boiler plate code in this method again to reflect (and to avoid unnecessary code was the goal in the first place).

Perhaps you have other ideas?

+3
java reflection junit aop
Nov 22 '11 at 21:12
source share
2 answers

You need a solution very similar to the answer Mark unit test as expected failure based on TestRule . Using the @Deprecated annotation example (you can use it here), you can paste the code if the annotation exists in the method. The Description class contains a list of method annotations.

public class ExecutionTest { public class BeforeExecution implements TestRule { public Statement apply(Statement base, Description description) { return statement(base, description); } private Statement statement(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { if (description.getAnnotation(Deprecated.class) != null) { // you can do whatever you like here. System.err.println("this will be run when the method has an @Deprecated annotation"); } base.evaluate(); } }; } } @Rule public BeforeExecution beforeExecution = new BeforeExecution(); // Will have code executed. @Deprecated @Test public void test1() { // stuff } // won't have code executed. @Test public void test2() { // stuff } } 
+9
Nov 22 '11 at 21:30
source share
— -

I would split the class into two. One with methods that you would annotate with @mine, and the other for others.

Then use @ before usual.

This does not add any standard code, and it will be easy to understand and maintain for future developers.

+2
Nov 22 2018-11-21T00:
source share



All Articles