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

时间:2018-09-16 20:23:52

标签: java spring-boot mockito mockmvc

我有一个暴露端点的REST控制器。命中此端点后,将调用void方法,然后该方法关闭并将文件推送到远程GitHub存储库。该代码运行良好。

为类编写单元测试时发生我的问题。我不希望实际的void方法被调用(因为它正在将文件推送到github)。调用该方法时,我已经将该方法模拟为doNothing(),但是由于某种原因该文件仍在推送中。我要去哪里错了?

下面是我的代码:

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

    }

}

我的测试。它正在传递,但是我认为正在被嘲笑的gitService.gitpush()方法正在将文件推送到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);
    }

}

如何完全避免调用.gitPush()方法?我只是在错误地嘲笑服务吗?

1 个答案:

答案 0 :(得分:1)

  1. 将@Before注释添加到您的设置方法中
  2. 将此添加到您的before方法MockitoAnnotations.initMocks(this)。

现在应该可以正常工作