1

In JUnit, I want to develop a framework that will intercept test method, say testA and will call before it a method beforeA() and call afterA() after. I want to use it to prepare data before and destruct it after the test run.

I cannot use regular @before and @after because they run before and after all tests. And I also do not want to divide the original test class to small tests.

Is this legitimate or this is not good because we are running test preparation and destruction inside the JUnit test method (and not in the before/after)?

I believe it is ok since in any event if I fail a test I should use assert (Test Failure) and not regular exception (Error/Exception) so it should not make a difference where exactly the test failed/exceptioned as long as I assert on test failure.

What do you think?

Amith
  • 6,818
  • 6
  • 34
  • 45
Ariel S
  • 13
  • 1
  • 3
  • Just use proper annotations: https://stackoverflow.com/questions/20295578/difference-between-before-beforeclass-beforeeach-and-beforeall – MaximSadym Nov 27 '19 at 11:49

2 Answers2

1

If you want to have data setup and clear methods that run before and after only certain tests within your test class, then you can just write those methods and call them in the test.

This way the methods are reusable and can be given appropriate names.

They could also be abstracted to an abstract super class so they could be shared around multiple test classes if that is what you need.

Something like this:

public class RandomTest {

    //Obviously these would need different access if moved to a super class
    private void setUpScenario1TestCase() {
        //Set up your test case
    }

    private void tearDownScenario1TestCase() {
        //Clear down the test case
    }

    @Test
    public void thatScenario1PerformsAsExpected() {
        setUpScenario1TestCase();  
        //Perform you tests
        tearDownScenario1TestCase()
    }
}

Personally, I see no problem with doing it in this manner, and in some cases I would suggest it. For things like setting up multiple expectations on multiple mocked dependencies, this is sometimes much clearer than having all the expectations in the test method itself.

The clarity of the test is as important than the test itself. So having these set up methods specifically named can be really helpful for keeping the tests concise.

I still think the standard @Before and @After are useful. For example guaranteeing instantiation of new objects for each test and tearing down any static test dependencies that you might have set up. However for test specific set up, they do fall a little short.

Dan Temple
  • 2,736
  • 2
  • 22
  • 39
1

Did you have a look at JUnit Rules?

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72