Search code examples
javaspring-bootmockitomockmvc

How to use Mockito to skip invoking a void method


I have a REST controller exposing an endpoint. When this endpoint is hit, a void method gets invoked and this method then goes off and pushes a file to a remote GitHub repo. The code is working beautifully.

My problem occurs when writing unit tests for the class. I don't want the actual void method to get invoked (because it's pushing a file to github). I've mocked the method to doNothing() when it's invoked, but the file is still being pushed for some reason. Where am i going wrong?

Below is my code:

//ApplicationController.java

@RestController
public class ApplicationController {

    @Autowired 
    GitService gitService;

    @GetMapping("/v1/whatevs")
    public String push_policy() throws IOException, GitAPIException {
        gitService.gitPush("Successfully pushed a fie to github...i think.");
        return "pushed the file to github.";
    }

}

//GitService.java

public interface GitService {

    public void gitPush(String fileContents) throws IOException, GitAPIException;

}

//GitServiceImpl.java

@Component
public class GitServiceImpl implements GitService {

    private static final Logger log = Logger.getLogger(GitServiceImpl.class.getName());

    @Override
    public void gitPush(String fileContents) throws IOException, GitAPIException {

        // prepare a new folder for the cloned repository
        File localPath = File.createTempFile(GIT_REPO, "");
        if (!localPath.delete()) {
            throw new IOException("Could not delete temporary file " + localPath);
        }

        // now clone repository
        System.out.println("Cloning from" + REMOTE_GIT_URL + "to " + localPath);

        try (Git result = Git.cloneRepository().setURI(REMOTE_GIT_URL).setDirectory(localPath)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GIT_USER, GIT_PASSWORD)).call()) {
            // Note: the call() returns an opened repository already which needs to be
            // closed to avoid file handle leaks!
            Repository repository = result.getRepository();

            try (Git git = new Git(repository)) {

                // create the file
                Path path = Paths.get(String.format("%s/%s", localPath.getPath(), "someFileName"));
                byte[] strToBytes = fileContents.getBytes();
                Files.write(path, strToBytes);

                // add the file to the repo
                git.add().addFilepattern("someFileName").call();

                // commit the changes
                String commit_message = String
                        .format("[%s] Calico yaml file(s) generated by Astra Calico policy adaptor.", GIT_USER);

                git.commit().setMessage(commit_message).call();

                log.info("Committed file to repository at " + REMOTE_GIT_URL);

                // push the commits
                Iterable<PushResult> pushResults = git.push()
                        .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GIT_USER, GIT_PASSWORD)).call();

                pushResults.forEach(pushResult -> log.info(pushResult.getMessages()));

            }
        } finally {
            // delete temp directory on disk
            FileUtils.deleteDirectory(localPath);
        }

    }

}

My test. It's passing, but the gitService.gitpush() method I thought was being mocked, is pushing a file to github.

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationControllerTest {

    @Autowired
    private MockMvc mockMvc;


    @Mock
    GitService gitService;

    //System under test
    @InjectMocks
    ApplicationController applicationController;


    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(applicationController).build();
    }


    @Test
    public void controllerShouldReturnStatus200Ok() throws Exception {
        Mockito.doNothing().when(gitService).gitPush(Mockito.anyString());

        mockMvc.perform(

                MockMvcRequestBuilders.get("/v1/whatevs")


                ).andExpect(MockMvcResultMatchers.status().isOk());
    }

    @Test
    public void someTest() {
        assertTrue(true);
    }

}

How can I keep the .gitPush() method from being invoked at all? Am I simply mocking the service incorrectly?


Solution

    1. Add @Before annotation to your setup method to
    2. Add this to your before method MockitoAnnotations.initMocks(this).

    It should work now