-1

I have a method that is not a regular test method. It is a cleanup method. I want to run it after some methods (some methods that are not test methods but are called from some test methods ).

How can do that using JUnit4?

PS: After and AfterClass are not a choice. I want to run a method after "some" non test methods (some methods that are called within test methods).

kamaci
  • 72,915
  • 69
  • 228
  • 366

3 Answers3

0

have you tried @AfterClass And @After ,@Before ,@BeforeClass ?

for the case of @AfterClass your method should be static . in these case your method would be launched once before all the Tests.

check this link. junit-beforeclass-and-afterclass-behavior-in-case-of-multiple-test-cases

Community
  • 1
  • 1
oussama.elhadri
  • 738
  • 3
  • 11
  • 27
  • AfterClass runs after class. It does not run after "some" non test methods. – kamaci Nov 16 '13 at 20:43
  • @kamaci "Some" non-test methods? Just call the method, or organize your tests differently, or use AOP. – Dave Newton Nov 16 '13 at 20:45
  • I just try to find a way to do this withing JUnit. Something like: "if a methods is called run another method." I do not use a AOP framework within my project. – kamaci Nov 16 '13 at 20:51
  • @kamaci "If a method is called run another method" is called "calling the method where you need to". There's no way to identify arbitrary methods and call them at arbitrary times, other than simply calling them when you need to, in Java or jUnit. That's not jUnit's purpose, either. – Dave Newton Nov 16 '13 at 20:56
0

You will need to call those methods manually or through AOP if you are using Spring.

Kashif Nazar
  • 20,775
  • 5
  • 29
  • 46
0

You could use a TestWatcher to listen to when the test has finished, & check the test-name to see if your code should be ran. E.g.:

@Rule
public TestRule runFooSomtimes = new TestWatcher() {

    public void foo() {
      //do stuff here
    }

    List<String> methodsToCheck = new ArrayList<String>() {{
        add("testMethodOne");
    }}

    @Override
    protected void finished(Description description) {
        if(methodsToCheck.contains(description.getMethodName())) {
            foo();
        }
    }
};

(Excuse any errors, away from an IDE at the moment, but should give an idea.)

anotherdave
  • 6,656
  • 4
  • 34
  • 65