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

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

问题描述

我不明白 JUnit 4.8 应该如何与 Hamcrest 匹配器一起工作.junit-4.8.jar<中定义了一些匹配器/code>org.hamcrest.CoreMatchers 中.同时,hamcrest-all-1.1.jarorg.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() 匹配器很感兴趣,但在这些 jars 中都找不到它.我需要别的东西吗?:)

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() 的新检查断言方法,该方法使用匹配器,并应提供更具可读性的测试代码和更好的失败消息.

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 库.

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天全站免登陆