This is the method I need to stub:
public static List<Path> getDiffedFilePaths(String repoDirectory, String relativeDirectoryPath) {
List<Path> diffedFiles = new ArrayList<>();
try {
ProcessBuilder processBuilder = new ProcessBuilder("git", "diff", "--name-only", relativeDirectoryPath);
processBuilder.directory(new File(repoDirectory));
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
diffedFiles.add(Paths.get(repoDirectory, line));
}
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
return diffedFiles;
}
This is how I stub it:
@Test
void testProcessCompilationUnitWithParamEnum() {
try {
AnnotationModifier modifier = new AnnotationModifier();
AnnotationModifier modifierSpy = Mockito.spy(modifier);
List<Path> mockDiffedFiles = Arrays.asList(
Path.of("mocked/file/path1"),
Path.of("mocked/file/path2")
);
Mockito.doReturn(mockDiffedFiles).when(modifierSpy).getDiffedFilePaths(Mockito.anyString(), Mockito.anyString());
// call the main method which consumes `getDiffedFilePaths`
The method should not even be called but it does. What might cause this issue? The exception I get is:
java.io.IOException: Cannot run program "git" (in directory ""): error=2, No such file or directory
Mockito version:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.10.0</version> <!-- Use the latest version -->
<scope>test</scope>
</dependency>
Mockito doesnot mock with static method . Either Remove the static keyword from method to make mockito works OR use approach as per https://www.baeldung.com/mockito-mock-static-methods