Using ParameterizedTest and MethodSource to run the same file-presence test with different inputs.
Transcribed from the original LinkedIn image post.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class Day29 {
final static String PATH = "/home/mohibulhasan/Downloads";
public boolean isFileAvailable(String relativeFilePath) {
List<String> fileNames = new ArrayList<>();
try (Stream<Path> paths = Files.walk(Paths.get(PATH))) {
fileNames = paths
.filter(Files::isRegularFile)
.map(Path::toAbsolutePath)
.map(Path::toString)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return fileNames.contains(relativeFilePath);
}
@ParameterizedTest(name = "{index} - Test with fileName : {0}")
@MethodSource("fileNameProvider")
public void testFilePresentOrNot(String fileName, boolean expectedResult) {
assertEquals(expectedResult, isFileAvailable(fileName));
}
public static Stream<Arguments> fileNameProvider() {
return Stream.of(
Arguments.of(PATH + "/data.json", true),
Arguments.of(PATH + "/404.txt", false)
);
}
}
|
The original LinkedIn graphic is preserved below.
