hamcrest 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: what is hamcrest

Hamcrest is library aim to created
readabale assertions. It can be used
separately by itself by importing the dependency
RestAssured already include Hamcrest library
so no separate depenceny requied.
Few common matchers I used :
is(.. )
not(..)
equalTo(..)
containString(...)
greaterThan(..)
lessThan(..)
hasSize(..)
hasItem(..) and hasItems(...)
Any many more.....


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 3: hamcrest

Hamcrest is a framework that assists writing software tests 
in the Java programming language. It supports creating customized 
assertion matchers.

Example 4: error: The method assertThat(T, Matcher) in the type MatcherAssert is not applicable for the arguments (List, Matcher>)

assertThat("test", anyOf(is("testing"), containsString("est")));