Run single JUnit test class multiple times with different instance variable values
-
20-12-2019 - |
Question
I have a JUnit test class whose every method will do something different based on the value of a local flag variable. Not that it matters too much but if the flag is true, the data gets saved in one format, if false it is saved in another, using a factory method to create an instance of the DAO object that is based on the flag. What I would like to do is not write two sets of tests considering that I only need to flip one switch.
I am running this in Maven. Is there a way to replicate the execution of this one test class while switching the value of the flag (using a setter?) between different test executions?
public class BifurcatedTest {
private boolean formatFlag = false;
@Test
public void testGadgetOne(){
Gadget gadg = new Gadget(1, "Gadget One");
GadgetDAO gadgDAO = GadgetAccessFactory.getGadgetDAO(this.formatFlag);
gadgDAO.save(gadg);
assert(true);
}
@Test
public void testGadgetTwo(){
Gadget gadg = new Gadget(2, "Gadget Two");
GadgetDAO gadgDAO = GadgetAccessFactory.getGadgetDAO(this.formatFlag);
gadgDAO.save(gadg);
assert(true);
}
public void setFormatFlag(boolean formatFlag) {
this.formatFlag = formatFlag;
}
}
UPDATE: I understand I could use a Suite
and inject the variable through the constructor and then list the class twice in the suite declaration. But ideally, I would like to use an annotation something similar to
@MultiExec("formatFlag=true;formatFlag=false");
Before the class declaration and that Maven would understand that annotation and run it as many times and do the specified injection.
Solution
I think your requirement was similar as DataProvider in TestNG.
Which you can do it in JUnit as Writing Java tests with data providers.