Search code examples
javatestng

How to debug testng tests which use dataproviders?


I have a testng test method which uses a dataprovider to get test inputs. I want to debug the test only when the test runs for the 2nd test data input. How do I do that ? How should I set the breakpoint ?

Here is some sample code.

@Test(dataProvider = "myDataProvider")
public void findStringInString(String input, String toFind, boolean found){
    Assert.assertEquals(finder(input, toFind), found, "Could not find " + toFind + " in " + input);
}

@DataProvider(name = "myDataProvider")
public static Object[][] stringSource()
{
    return new Object[][] {
        {"hello", "hell", true},
        {"nice", "iced", false},
        {etc...}
    };
}

PS - As an aside, does this code look like an anti-pattern or bad practice ?


Solution

  • The easiest way of determining where to setup the debug point is to maintain a counter that checks which data provider iteration is being run and then when the value reaches your desired value, do a debug print statement and set the breakpoint in that line.

    Here's a sample

    import java.util.concurrent.atomic.AtomicInteger;
    import org.testng.annotations.DataProvider;
    import org.testng.annotations.Test;
    
    public class SampleTestCase {
    
      private final AtomicInteger counter = new AtomicInteger(1);
    
      @Test(dataProvider = "getData")
      public void testMethod(String s) {
        if (counter.getAndIncrement() == 2) {
          System.err.println("Debug mode on"); //Set a breakpoint on this line
        }
        System.err.println("Hello " + s);
    
      }
    
      @DataProvider
      public Object[][] getData() {
        return new Object[][]{
            {"TestNG"},{"Spring"},{"Selenium"}
        };
      }
    
    }
    

    As an aside, does this code look like an anti-pattern or bad practice ?

    I dont think a lot can be said by just looking at the skeleton code. There's hardly anything in the sample that you shared that we can use to suggest.