Powered By Blogger

Saturday, July 23, 2011

TestNg DataProvider Example

Data providers are used to feed data to a test method, often when a method is to be tested against different scenarios (or data sets), which are expected to give the same result.
This is an illustration of a data provider.

================================================================

@Test(dataProvider = "incorrect-data",
                   expectedExceptions = {InvalidInputException.class}, enabled = true)
public void testCreateWithIncorrectData(Byte bt, byte[] data) {
          timeStamp.create(bt.byteValue(), data);
}

@DataProvider(name = "incorrect-data")
public Object[][] incorrectData() {
          return new Object[][]{
                {new Byte((byte)1), new byte[]{(byte)0xF3, 0, -127, 100, 120, 0, 0}},
                {new Byte((byte)1), new byte[]{(byte)0xF1, 0, -127, 5, 0, 0, 0}},
                {new Byte((byte)3), new byte[]{(byte)0xF1, 0, -127, 5, 0, 0, 0}},
                {new Byte((byte)3) ,new byte[]{(byte)0xF3, 0, 60, 100, 120, 0, 0}}
        };
}

================================================================

The example above tests a creation of time stamps for incorrect data. The data provider (annotated with @DataProvider) provides data to the test method (annotated with @Test).

Annotations;

  • @Test: Methods annotated with this will be considered as a test method. The attribute dataProvider configures the data provider to the test case, expectedExceptions is to specify the exceptions expected to be thrown and enable is used to make the test method enabled or disabled.
  • @DataProvider: Methods annotated with this are data providers. A data provider should have a name which is given as the 'name' attribute in order to be used by a test method.

The method incorrectData() returns a two-dimensional object array of size, 4. Each of the four arrays has two elements, which are arguments to the test method (testCreateWithIncorrectData(Byte, byte[])). Data types of the elements of each secondary array should exactly match the parameters of the test method. Since there are four sets of data, the test method will be executed four times, in one run of the test case. All four runs of the method should throw InvalidInputException exception if the test case is to pass.

thanks,
Shyarmal.

No comments:

Post a Comment