How to give null value to a parameter when using @FileParameters of JUnitParams

6.3k views Asked by At

I try to use FileParameters annotation of JUnitParamsRunner. I cannot give null to a variable. The code and test file is below.

@RunWith(JUnitParamsRunner.class)
public class PasswordCheckerFileParameterizedTest {


    @Test
    @FileParameters("src/test/resources/testScenarios.csv")
    public void checkPasswordIsValid_checkMultipleCase(String password,boolean expectedResult){
        PasswordChecker passwordChecker = new PasswordChecker();
        assertEquals(expectedResult,passwordChecker.checkPasswordIsValid(password));
    }
}

testScenarios.csv

,false
sD1.,false
ssfdsdfsdf234.,false
SEWERWER234.,false
ssfdsdfsdSDFSDF.,false
ssfdsdfsdSDFSDF3234,false
ssfdsdfsdSDFSDF23.,true
2

There are 2 answers

0
Adam Michalik On BEST ANSWER

This does not work by default since FileParameters uses IdentityMapper to map lines in the file to parameters and that works as if you used the @Parameters({"aaa,bbb", "ccc,ddd"} syntax in which you cannot provide a null value - writing null will give you a String saying "null".

You can however provide your own mapper by means of FileParameters#mapper. It has to return a mapped Object[][] (same format as if you used a method parameter provider for @Parameters(method = ...)). Then you need to decide in what way you'll mark null in your file.

A sample mapper that treats the string "xxx" as a null marker would look like this:

public class XxxToNullMapper implements DataMapper {
    @Override
    public Object[] map(Reader reader) {
        return new BufferedReader(reader).lines()
                .map(line -> line.split(","))
                .map(columns ->
                        Stream.of(columns)
                                .map(column -> column.equals("xxx") ? null : column)
                                .collect(Collectors.toList()).toArray()
                )
                .collect(Collectors.toList()).toArray();
    }
}

Usage:

@Test
@FileParameters(
        value = "/test.csv",
        mapper = XxxToNullMapper.class
)
public void xxxIsNullFileParameters(String a, String b) {
    System.out.println("Params are: " + a + " (is null? " + (a == null) + "), " + b + " (is null? " + (b == null) + ")");
}

/test.csv:

aaa,bbb
aaa,xxx

Prints

Params are: aaa (is null? false), bbb (is null? false)
Params are: aaa (is null? false), null (is null? true)
1
Brad Cupit On

I haven't used @FileParameters but for normal @Parameters you can use the @Nullable annotation:

@Test
@Parameters({"null, , null"})
public void yourTest(@Nullable String nullable, String blank, String textIsNull) {
  //  important part ^^^^^^^^^         but no @Nullable here ^^

  assertThat(nullable).isNull();         // it worked!
  assertThat(blank).equals("");
  assertThat(textIsNull).equals("null"); // not null but the string "null"
}