0

Consider an example:

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderExampleTest {
    @Test(dataProvider="data")
    public void testDataProvider(int p1, String p2) {
        /*
        assert block for all p1 and p2 parameters
        */

        // ???
        // how to put p1 and p2 specific assertions here?
        //jst for example
        if (p2.equals("myString")) {
            //asserts for myString
        }
        if (p2.equals("otherString")) {
            //asserts for otherString
        }
    }

    @DataProvider
    public Object[][] data() {
        return new Object[][]{/*dozen objects here*/};
    }
}

The example is simplified, in real life p1 and p2 can be very complex objects with subclasses which require complex assertions.

Does testng provides some api to put parameter's specific assertion somewhere, but without creating too long if or switch conditions? (For my opinion if and switch is like duplicate business logic in test and should be avoided)

Also what data driven development approach suggest to do in such situations when all elements can be checked with general algorithm, but only a few with specific?

VVN
  • 1,607
  • 2
  • 16
  • 25
Cherry
  • 31,309
  • 66
  • 224
  • 364
  • 1
    Can you provide more details? If the problem is only about assert of complex objects---> Every object has an equals method.For comparing two complex objects, you call their equals method,which you can override and in turn call equals methods of any nested object types.This kind of design pattern is called visitor pattern. All TestNG does is calls the equals method, how and what you put into the method is really upto you. – Surbhi Sharma Feb 26 '16 at 08:48

2 Answers2

0

I would probably organize my tests differently. Based on the testName, the dataprovider would return data. I would have three tests

  1. testCommons
  2. testString1
  3. testOtherString

Pass to the dataprovider the method argument. The dataprovider decides on sending data based on the name of the test.

niharika_neo
  • 8,441
  • 1
  • 19
  • 31
0

You can organize your assertions together by using a framework like Hamcrest or Truth. In Hamcrest you can create custom matchers and in Truth you can create your own subjects. See the Writing custom matchers section of The Hamcrest Tutorial and Truth - Extensibility for details.

You can also simply organize assertions by creating static utility methods that do multiple assertions in them and if you want to do so with more fluent code then you can convert your tests from Java to something a language like Kotlin that supports extension functions (see also Converting an existing Java file to Kotlin with J2K).

mfulton26
  • 29,956
  • 6
  • 64
  • 88