簡體   English   中英

使用 Jgit 使用 Mockito 編寫單元測試

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM