Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mockito invokes method even after specyfing not to

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading