如何使用 Mockito 跳过调用 void 方法
How to use Mockito to skip invoking a void method
我有一个暴露端点的 REST 控制器。当命中此端点时,将调用一个 void 方法,然后此方法将关闭并将文件推送到远程 GitHub 存储库。代码运行良好。
我的问题出现在为 class 编写单元测试时。我不希望调用实际的 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)。
现在应该可以了
我有一个暴露端点的 REST 控制器。当命中此端点时,将调用一个 void 方法,然后此方法将关闭并将文件推送到远程 GitHub 存储库。代码运行良好。
我的问题出现在为 class 编写单元测试时。我不希望调用实际的 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)。
现在应该可以了