使用 Jgit 使用 Mockito 编写单元测试

时间:2021-07-10 10:52:01

标签: java junit mockito 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());
    }

提前致谢

1 个答案:

答案 0 :(得分:0)

您应该避免使用静态方法。如果您无法模拟 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

相关问题