Java 如何使用Mockito跳过调用void方法

Java 如何使用Mockito跳过调用void方法,java,spring-boot,mockito,mockmvc,Java,Spring Boot,Mockito,Mockmvc,我有一个REST控制器公开一个端点。当命中该端点时,将调用一个void方法,然后该方法关闭并将文件推送到远程GitHub repo。代码运行得很好 我的问题发生在为类编写单元测试时。我不想调用实际的void方法,因为它正在将文件推送到github。在调用该方法时,我将其模拟为不执行任何操作,但由于某些原因,仍在推送该文件。我哪里做错了 下面是我的代码: //ApplicationController.java @RestController public class ApplicationCon

我有一个REST控制器公开一个端点。当命中该端点时,将调用一个void方法,然后该方法关闭并将文件推送到远程GitHub repo。代码运行得很好

我的问题发生在为类编写单元测试时。我不想调用实际的void方法,因为它正在将文件推送到github。在调用该方法时,我将其模拟为不执行任何操作,但由于某些原因,仍在推送该文件。我哪里做错了

下面是我的代码:

//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);
        }

    }

}
我怎样才能阻止.gitPush方法被调用呢?我只是在错误地嘲笑服务吗

将@Before注释添加到设置方法中 将此添加到您的before方法MockitoAnnotations.initMocksthis。
它现在应该可以工作了

您似乎没有在任何地方初始化您的Mockito mock。我错过什么了吗?您可以将MockitoAnnotations.initMocksthis添加到测试中的@Before方法中。或者看看@DawoodibnKareem谢谢-我没有用Before注释来注释setup方法,我也没有初始化mock。现在可以了。
@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);
    }

}