I have just started learning JUnit very recently and came across the following problem.
Have a look at the following class
class MyClass { String a; public MyClass(String a) { this.a=a; String doSomething(String a) { if( a.isEmpty() ) return "isEmpty"; else return"isNotEmpty"; } I want to test the above method for both the conditions. If I proceed with the general structure of writing testcases it will look something like this:
class MyClassTest { MyClass myClass; @BeforeEach void setUp() { myClass=new MyClass("sampleString"); } @Test void doSomethingTest() { Assertions.equal("isNotEmpty", myClass.doSomething()); } } However, for testing the empty string condition I will need another setup method where instead of "sampleString" I pass an empty string.
Following are the approaches I could think of and the questions for each:
- Not use setUp at all and instead initialize the class in the individual test method. However, if let's say there are 10 testcases; 5 of which require empty string and rest
"sampleString"then this doesn't make sense. Again, we can have a separate method for this repetitive code and call it individually in each testcase but then that defeats the purpose of having a steup method. Lets say I wanted to use two different setup methods, is there a way to do so? - Have a parameterized setup. I don't know if this is possible though. If yes, please share some useful links for this.
- Use TestFactory. I tried reading up about this, but couldn't find an example for this specific case. If you have any, please share.
This example has been kept simple for illustrative purposes.
@org.junit.jupiter.api.Nestedtest classes for complex setup scenarios, they may contain@BeforeEachtest setup methods too.