yeg*_*256 87 java junit hamcrest
我无法理解JUnit 4.8应该如何与Hamcrest匹配器一起使用.有内部定义了一些匹配器junit-4.8.jar
在org.hamcrest.CoreMatchers
.同时,也有一些其他的匹配器hamcrest-all-1.1.jar
中org.hamcrest.Matchers
.那么,去哪里?我应该在项目中明确包含hamcrest JAR并忽略JUnit提供的匹配器吗?
特别是,我对empty()
匹配器很感兴趣,并且无法在任何这些罐子中找到它.我需要别的吗?:)
还有一个哲学问题:为什么JUnit将org.hamcrest
包装包含在自己的发行版中而不是鼓励我们使用原始的hamcrest库?
Ste*_*ner 50
如果您使用的Hamcrest版本大于或等于1.2,那么您应该使用junit-dep.jar
.这个jar没有Hamcrest类,因此你可以避免类加载问题.
由于JUnit 4.11 junit.jar
本身没有Hamcrest类.不再需要junit-dep.jar
了.
cpa*_*ter 49
junit提供了名为assertThat()的新检查断言方法,该方法使用Matchers并且应该提供更易读的测试代码和更好的失败消息.
要使用它,junit中包含一些核心匹配器.您可以从这些开始进行基本测试.
如果你想使用更多的匹配器,你可以自己编写或使用hamcrest lib.
以下示例演示如何在ArrayList上使用空匹配器:
package com.test;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class EmptyTest {
@Test
public void testIsEmpty() {
List myList = new ArrayList();
assertThat(myList, is(empty()));
}
}
Run Code Online (Sandbox Code Playgroud)
(我在buildpath中包含了hamcrest-all.jar)
Tom*_*icz 25
不完全回答你的问题,但你一定要尝试FEST-Assert流畅的断言API.它与Hamcrest竞争,但有一个更容易的API,只需要一个静态导入.以下是cpater使用FEST 提供的代码:
package com.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
public class EmptyTest {
@Test
public void testIsEmpty() {
List myList = new ArrayList();
assertThat(myList).isEmpty();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:Maven坐标:
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<version>1.4</version>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
sou*_*ser 17
此外,如果正在使用JUnit 4.1.1 + Hamcrest 1.3 + Mockito 1.9.5,请确保未使用mockito-all.它包含Hamcrest核心类.请改用mockito-core.以下配置有效:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.1.1</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
Run Code Online (Sandbox Code Playgroud)