[英]Writing Unit test with Mockito with Jgit
在测试我的代码时,我是 Mockito/PowerMockito 的新手(因为它是一个静态方法)。 我无法为此方法编写测试,因为它包含 fileList 和 Jgit 方法,任何人都可以展示我如何对此特定方法执行测试。
public static String addAndCommitUntrackedChanges(final File gitFile, final String branchName,
final String commitMessage, List<String> filesList)
throws IOException, GitAPIException {
final Git openedRepo = Git.open(gitFile);
openedRepo.checkout().setCreateBranch(true).setName(branchName).call();
AddCommand add = openedRepo.add();
for (final String file: filesList) {
Path filepath = Paths.get(file); //file absolute Path
final Path repoBasePath = Paths.get("/", "tmp", "PackageName"); //file base common path
final Path relative = repoBasePath.relativize(filepath); //Remove the repoBasePath from filpath
add.addFilepattern(relative.toString());
}
add.call();
// Create a new commit.
RevCommit commit = openedRepo.commit()
.setMessage(commitMessage)
.call();
//Return the Latest Commit_Id
return ObjectId.toString(commit.getId());
}
提前致谢!
您应该避免使用静态方法。 如果你不能模拟它,你将如何测试addAndCommitUntrackedChanges
客户端?
为了使addAndCommitUntrackedChanges
更具可测试性,引入一个 GitWrapper 接口:
interface GitWrapper {
Git open(File f);
}
有一个实现:
class DefaultGitWrapper implements GitWrapper {
public Git open(File f) {
return Git.open(f);
}
}
并将您的方法的签名更改为:
public static String addAndCommitUntrackedChanges(
GitWrapper gitWrapper,
final File gitFile,
final String branchName,
final String commitMessage,
List<String> filesList)
并使用GitWrapper
而不是Git
的静态实例。
在Git
的特殊情况下,不需要包装器,因为您可以只传递一个Git
实例,它可以正常模拟,但是当您真的有一个仅提供静态方法的第三方类时,这是一个必要的解决方案。
然后你可以模拟你需要模拟的东西来编写单元测试,它看起来像(这是未编译的代码):
class TestAddAndCommitUntrackedChanges {
@Mock
GitWrapper gitWrapper;
@Mock
Git git;
@Mock
CheckoutCommand checkoutCommand;
@Mock
AddCommand addCommand;
@Test
public void testBehaviour() {
List<String> files = List.of("/tmp/PackageName/foo", "/tmp/PackageName/bar");
File gitFile = new File("gitFile");
when(gitWrapper.open(gitFile)).thenReturn(git);
when(git.checkout()).thenReturn(checkoutCommand);
when(checkoutCommand.setName("theBranch"))
.thenReturn(checkoutCommand);
when(git.add()).thenReturn(addCommand);
assertEquals(
"thecommitid",
addAndCommitUntrackedChanges(
gitWrapper, gitFile, "theBranch",
"the commit message", files)
);
verify(checkoutCommand).call();
verify(addCommand).addFilePattern("foo");
verify(addCommand).addFilePattern("bar");
verify(addCommand).call();
}
}
您还需要模拟和验证CommitCommand
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.