gpt4 book ai didi

java - org.junit.Assert.assertThat 比 org.hamcrest.MatcherAssert.assertThat 好吗?

转载 作者:太空狗 更新时间:2023-10-29 22:53:38 39 4
gpt4 key购买 nike

我是 JUnit 和 Hamcrest 的新手,希望获得最佳实践建议,以便我可以决定首先研究哪些文档。

对于初学者来说,这些 assertThat 方法中哪个更好?

  1. org.junit.Assert.assertThat(来自 junit-4.11.jar)
  2. org.hamcrest.MatcherAssert.assertThat(来自 hamcrest-core-1.3.jar)

据一个人说,去年,"JUnit has the assertThat method, but hamcrest has its own assertThat method that does the same thing." .

根据今年早些时候的消息,Hamcrest "could potentially give better error messages because the matcher is called to describe the mismatch" .

很难说在这些帖子中比较了 Junit 和 Hamcrest 的哪个版本。所以我想要一个基于最新发布版本的推荐。

最佳答案

几乎完全一样。

最新版本的 JUnit 现在包括 hamcrest。

其实org.junit.Assert.assertThat的方法签名是

public static <T> void assertThat(T actual,
org.hamcrest.Matcher<T> matcher)

您会注意到它使用了 hamcrest 匹配器。

您可能仍然希望包括您自己的 hamcrest 版本,因为 JUnit 更新不频繁,并且可能并不总是使用最新版本的 hamcrest。

根据maven pom,JUnit 4.11 使用 hamcrest 1.3,我认为这是撰写本文时最新的版本。

编辑我刚刚读了你的第二篇文章 http://blog.code-cop.org/2014/02/assert-or-matcherassert.html它描述了 hamcrest 中的 2 个细微差别 assertThat这使它更有用:

  1. 当匹配失败时,错误消息包括不同之处,而不是“预期的 X 但实际是 Y”。通过实现 describeMismatch(),定制的 hamcrest 匹配器可能会包含更多关于到底出了什么问题的详细信息。 .
  2. assertThat使用 T actual, Matcher<? super T> matcher 的 hamcrest 签名不同这允许匹配器成为父类(super class)型(如匹配器比较整数和 double )。这通常无关紧要,但当您需要它时,这是一个不错的功能。

所以使用org.hamcrest.MatcherAssert.assertThat .

关于java - org.junit.Assert.assertThat 比 org.hamcrest.MatcherAssert.assertThat 好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27256429/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com