如何一起使用JUnit和Hamcrest? [英] How to use JUnit and Hamcrest together?

查看:284
本文介绍了如何一起使用JUnit和Hamcrest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解JUnit 4.8如何与Hamcrest匹配器一起使用。 junit-4.8中定义了一些匹配器 org.hamcrest.CoreMatchers 中的.jar 。同时在其他匹配器。 jarrel =noreferrer> hamcrest-all-1.1.jar org.hamcrest.Matchers 。那么,去哪里?我应该在项目中明确包含hamcrest JAR并忽略JUnit提供的匹配器吗?

I can't understand how JUnit 4.8 should work with Hamcrest matchers. There are some matchers defined inside junit-4.8.jar in org.hamcrest.CoreMatchers. At the same time there are some other matchers in hamcrest-all-1.1.jar in org.hamcrest.Matchers. So, where to go? Shall I explicitly include hamcrest JAR into the project and ignore matchers provided by JUnit?

特别是,我对 empty()感兴趣 matcher,无法在任何这些罐中找到它。我需要别的东西吗? :)

In particular, I'm interested in empty() matcher and can't find it in any of these jars. I need something else? :)

还有一个哲学问题:为什么JUnit包含 org.hamcrest 包而不是鼓励我们使用原始的hamcrest库?

And a philosophical question: why JUnit included org.hamcrest package into its own distribution instead of encouraging us to use original hamcrest library?

推荐答案

junit提供了一个名为assertThat()的新检查断言方法,该方法使用Matchers并且应该提供更易读的测试代码和更好的失败消息。

junit provides new check assert methods named assertThat() which uses Matchers and should provide a more readable testcode and better failure messages.

要使用它,junit中包含一些核心匹配器。您可以从这些开始进行基本测试。

To use this there are some core matchers included in junit. You can start with these for basic tests.

如果您想使用更多匹配器,您可以自己编写或使用hamcrest lib。

If you want to use more matchers you can write them by yourself or use the hamcrest lib.

以下示例演示如何在ArrayList上使用空匹配器:

The following example demonstrates how to use the empty matcher on an 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()));

    }
}

(我包括了hamcrest-all我的构建路径中的.jar)

(I included the hamcrest-all.jar in my buildpath)

这篇关于如何一起使用JUnit和Hamcrest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆