what is hamcrest matcher code example
Example 1: what is hamcrest for
Hamcrest is a framework for writing matcher objects
allowing 'match' rules to be defined declaratively.
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class BiscuitTest {
@Test
public void testEquals() {
Biscuit theBiscuit = new Biscuit("Ginger");
Biscuit myBiscuit = new Biscuit("Ginger");
assertThat(theBiscuit, equalTo(myBiscuit));
Example 2: error: The method assertThat(T, Matcher) in the type MatcherAssert is not applicable for the arguments (List, Matcher>)
assertTrue(result instanceof String);
// error message:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertTrue(Assert.java:52)
// ...
assertEquals(String.class, result.getClass());
// error message:
java.lang.NullPointerException
at com.vogella.hamcrest.HamcrestTest.test(HamcrestTest.java:30)
// ....
assertThat(result, instanceOf(String.class));
// error message:
java.lang.AssertionError:
Expected: an instance of java.lang.String
but: null
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
// ...