java - 如何使用 Mockito 跳过调用 void 方法
问题描述
我有一个暴露端点的 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() 方法根本不被调用?我只是错误地嘲笑服务吗?
解决方案
- 将 @Before 注释添加到您的设置方法以
- 将此添加到您之前的方法 MockitoAnnotations.initMocks(this)。
它现在应该可以工作
推荐阅读
- xml - 隐藏自定义(/)页面的标题odoo v12
- android - 向不同客户发布/推出同一应用程序的不同版本/定制的选项?
- c++ - Boost intrusive list 中有很多编译错误
- r - 分析 R 中的数据,我想将图表导出到 powerpoint
- mono - 如何结合 Mono 和 Flux 作为参数来创建新的 Mono?
- google-chrome - 如何在 Chrome 74+ 中禁用 CORB
- php - 如何将两个 svg 动画放在一列中?
- r - 有没有可以用权重聚类的算法?
- react-native - 如何修改 SafeAreaView 中的填充?
- vue.js - 在 VueJS 中,当我有唯一字符串或数字数组时,是否可以将 :key 属性绑定到元素值?