Search code examples
javatestingjava-streamtestngtestng-dataprovider

Passing lambdas as testng parameters using DataProvider?


I was wondering if there is a way to pass lambdas from testng's data providers. So I want to do something like the following:

    @DataProvider(name="checkProvider")
    public Object[][] checkProvider() {
        return new Object[][]{
            "Some string to test", (String string) -> string.length() > 2 //A predicate on how to test response
        }
    }

And after that have some test like so

@Test(dataProvider="checkProvider")
public void testsomething(String s, Predicate<String> checker) {
    //so some operation on s to get a string I want to check
    Assert.assertTrue(checker.check(someString));
}

Right now I'm not able to do this as I get Target type of lambda conversion must be an interface. Does anyone have an idea on how to do this or even an alternative would be good so I could achieve the desired functionality.

EDIT: The answer is in the first comment. I was trying to pass a lambda directly but if you first declare it and then pass it in Object[][] then it works fine.


Solution

  • As requested here is my comment as an answer:

    You can do:

    Predicate<String> p = string -> string.length() > 2; 
    public Object[][] dataProviderMethod() { 
        return new Object[][] { { "Some string to test" }, { p } }; 
    } 
    

    I don't know how useful it is with TestNG.