Multiple Junit Tuning and One Test

I want to write a test that installs in several ways, but expect them to produce the same result. Basically how

@Before public void setUp1(){ obj.addDataThisWay(data); } @Before public void setUp2(){ obj.addDataThatWay(data); } @Test public void testResult(){ assertEquals(obj.getResult(),1); } 

I want the test to run twice, one for setUp1()->testResult() , the other for setUp2()->testResult() Is this possible?

+6
source share
5 answers

I do not know. You must either deploy this to two separate tests (and, if you want, output the statements to general, closed, not @Test ), or you can use parameterized tests .

+6
source
 public void testWithSetup1() { callSetup1Here(); ..... } public void testWithSetup2() { callSetup2Here(); ..... } 

I don’t think there is another way to do what you ask.

+4
source

I just guess, but you can’t use inheritance? creating an abstract class using the testResult () method and concrete classes with each of the setUp () methods?

+2
source

With TestNG, you would use for this group:

 @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 "g1" group, it will run setUp1 () -> testResult. If you run the "g2" group, it will run setUp2 () -> testResult.

In addition, like the commentator mentioned above, you can use data providers to pass various parameters to your testing 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); } 
+1
source

JUnit Parameterized can do the trick.

Changing the code in the original question using the Parameterized parameter should look something like this:

 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); } } 
0
source

Source: https://habr.com/ru/post/891132/


All Articles