MasterJoe
MasterJoe

Reputation: 2355

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 ?

Upvotes: 1

Views: 506

Answers (2)

Domadin
Domadin

Reputation: 577

You can filter out irrelevant tests by asserting your test parameters in a test body and throw new SkipException("message") for every test except the one you want to debug. It's very convenient to use this approach in combination with a test name parameter in data providers.

@Test(dataProvider = "provider")
public void testMethod(String name, int i) {
    if (!name.equals("Second test")) {
        throw new SkipException("Skipping this test case"); // Only "Second test" test won't be skipped
    }
    System.out.println("Hello " + i); //Set a breakpoint on this line
}

@DataProvider
public Object[][] provider() {
    return new Object[][]{
            {"First test", 1},
            {"Second test", 2},
            {"Third test", 3}
    };
}

Result: test results

Upvotes: 0

Krishnan Mahadevan
Krishnan Mahadevan

Reputation: 14746

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.

Upvotes: 1

Related Questions