Junit multiple setup and single test
I want to write a test that perform Setup in several ways but expect them to produce the same output. Basically like
@Before
public void setUp1(){
obj.addDataThisWay(data);
}
@Before
public void setUp2(){
obj.addDataThatWay(data);
}
@Test
public void testResult(){
assertEquals(obj.getResult(),1);
}
I want it the test to run twic开发者_JS百科e, one for setUp1()->testResult()
, the other one for setUp2()->testResult()
Is that possible?
Not to my knowledge. You must either turn this into two separate tests (and extract the assertions to a common, private, non-@Test
method if you want to), or you can use parameterized tests.
public void testWithSetup1() {
callSetup1Here();
.....
}
public void testWithSetup2() {
callSetup2Here();
.....
}
I don't think there is any other way to do what you are asking.
I am just guessing now, but can't you use inheritance? creating an abstract class with your testResult() method and concrete classes with each one of the setUp() methods?
With TestNG, you would use groups for this:
@BeforeMethod(groups = "g1")
public void setUp1(){
obj.addDataThisWay(data);
}
@BeforeMethod(groups = "g2")
public void setUp2(){
obj.addDataThatWay(data);
}
@Test(groups = { "g1", "g2" })
public void testResult(){
assertEquals(obj.getResult(),1);
}
If you ask TestNG to run the group "g1", it will run setUp1() -> testResult. If you run the group "g2", it will run setUp2() -> testResult.
Also, like the commenter above said, you can use data providers to pass different parameters to your test method:
//This method will provide data to any test method that declares that its Data Provider
//is named "test1"
@DataProvider(name = "test1")
public Object[][] createData1() {
return new Object[][] {
{ "Cedric", new Integer(36) },
{ "Anne", new Integer(37)},
};
}
//This test method declares that its data should be supplied by the Data Provider
//named "test1"
@Test(dataProvider = "test1")
public void verifyData1(String n1, Integer n2) {
System.out.println(n1 + " " + n2);
}
JUnit Parameterized can do the trick.
Modifying the code in the original question using Parameterized should look something like the following:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class MyTest {
private Object obj;
public MyTest(boolean addDataThisWay) {
if (addDataThisWay)
obj.addDataThisWay(data);
else
obj.addDataThatWay(data);
}
@Parameters
public static Collection<Object[]> differentTestSettings() {
return Arrays.asList(new Object[][]{
{true},
{false}
});
}
@Before
public void setUp(){
// any additional setup required
}
@Test
public void testResult(){
assertEquals(obj.getResult(),1);
}
}
精彩评论