Java中使用了Mockito Matchers和Hamcrest Matchers来创建测试断言,但它们具有不同的目的并具有不同的特征。
Mockito Matchers
使用模拟对象时,Mockito Matchers主要用于设置期望或验证。这些匹配器返回要匹配的对象的类型,这使它们可以直接用作模拟对象的方法调用中的参数。例如,`org.mockito.matchers.any(integer.class)`返回一个``整数'',使其适用于方法固执或验证,例如wheres(mockfoo.getBarbarbyIndex(yyy(nyry(integer.class.class.class.class.class.class.class))))`[1]。
Mockito Matchers旨在与Mockito的模拟框架无缝地工作,从而使您可以定义模拟对象上的方法调用灵活期望。但是,它们通常不与“断言”陈述一起使用,这些陈述通常与Hamcrest相关。
Hamcrest比赛
另一方面,Hamcrest Matchers旨在与“断言”陈述用于测试中的条件。他们返回一个“匹配器”对象,这是一个谓词,可用于评估是否满足条件。 Hamcrest匹配器具有很高的灵活性,可以使用逻辑运算符(例如allof',anyof'和``不创建复杂的断言)组合[2] [3]。
Hamcrest匹配器与JUNIT和其他测试框架一起广泛使用,以编写清晰可读的测试断言。它们提供了流利的API,使测试代码更加自我记录且易于理解。例如,`sustertthat(“ hello”,qualto(“ hello”))`清楚地传达了断言的意图[7]。
Mockito和Hamcrest之间的整合
如果您想在需要Mockito Matcher(例如,固执或验证方法调用)的上下文中使用Hamcrest Matcher,则Mockito提供了“ argthat”方法。此方法使您可以包装Hamcrest Matcher并将其用作摩索哥匹配器。例如,`何时(mockfoo.getBarbyDouble(argthat(coleto(1.0,0.001)))))`使用hamcrest匹配器指定双重值的条件,并具有一定的精度[1] [5]。
在Mockito 2及以后,与Hamcrest的集成通过“ MockitoHamcrest”类处理,该类提供了一种专门设计用于与Hamcrest Matchers合作的方法[5] [10]。这种脱钩有助于避免Mockito和Hamcrest库之间的版本冲突。
总而言之,Mockito Matchers主要用于模拟和固执,而Hamcrest Matchers则用于断言。两者都可以通过利用“ argthat”方法将hamcrest匹配器集成到Mockito的模拟框架中,从而有效地使用测试。
引用:[1] https://stackoverflow.com/questions/8348046/mockitos-matcher-vs-hamcrest-matcher
[2] https://www.javacodegeeks.com/2015/11/hamcrest-matchers-tutorial.html
[3] https://www.vogella.com/tutorials/hamcrest/article.html
[4] https://support.intershop.com/kb/go.php/a/enfdevdoc/pages/1827636063/guide+-+-+7.10+migration+mockito+mockito +1+1+to+mockito+2
[5] https://site.mockito.org/javadoc/current/org/mockito/mockito/hamcrest/mockitohamcrest.html
[6] https://www.baeldung.com/hamcrest-text-matchers
[7] https://automatenow.io/complete-guide-to-hamcrest-matchers/
[8] https://www.scalatest.org/scaladoc/3.0.7/org/scalatest/matchers.html
[9] https://hamcrest.org/javahamcrest/tutorial
[10] https://www.lambdatest.com/automation-testing-testing-advisor/selenium/methods/org.mockito.hamcrest.mockitohamcrest.argthat