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
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)