JUnit 3.8.1 Example Program for Hamcrest 1.3

Q

Where can I find an example program to use JUnit 3.8.1 with Hamcrest 1.3?

✍: FYIcenter.com

A

Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. The hamcrest-generator-1.3.zip contains a some examples on how to use Hamcrest with JUnit 3.x and JUnit 4.x in the "hamcrest-examples" folder.

Here is the source of ExampleWithAssertThat.java:

package org.hamcrest.examples.junit3;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import junit.framework.TestCase;

/**
 * Demonstrates how Hamcrest matchers can be used with assertThat()
 * using JUnit 3.8.x.
 *
 * @author Joe Walnes
 */
public class ExampleWithAssertThat extends TestCase {

    public void testUsingAssertThat() {
        assertThat("xx", is("xx"));
        assertThat("yy", is(not("xx")));
        assertThat("i like cheese", containsString("cheese"));
    }

}

This example shows that:

  • The ExampleWithAssertThat class extends the JUnit 3.8.1 TestCase class, so it can be executed by the TestRunner of JUnit 3.8.1.
  • The testUsingAssertThat() method is a test method recognized by JUnit 3.8.1.
  • The assertThat() method is provided by the org.hamcrest.MatcherAssert class.

Back to FAQ for Hamcrest - Library of Matchers.

2016-03-25, 2496🔥, 0💬