Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hamcrest
java
unit testing

What are Hamcrest Assertions?

lfrah Dar

Hamcrest is used for unit testing in Java. The goal of Hamcrest is to make it easier to read and write test cases.

We use Hamcrest to write the matcher objects that allow us to define the match rules declarative.

We can use Hamcrest after we import it into our file.

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

Code

Let’s run the code:

package demopackage;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.*;                

public class hamcrestTest { 

  //assertThat check first Array is equals to Second Array
  @Test
   public void demo() {
      assertThat(new int[] { 1, 2, 3 }, equalTo(new int[] { 1 , 2 }));
   }
    
}

In the above code, our test case fails because both arrays are not equal.

assertThat is the traditional assertion method, and equalTo is the matcher provided by Hamcrest.

After we run this code, we get the following output:

Expected: [<1>, <2>]
     but: was [<1>, <2>, <3>] 

Benefits

  • Failure messages of test cases are more understandable.
  • Test cases are readable and typeable.
  • Provides custom assertions.

RELATED TAGS

hamcrest
java
unit testing

CONTRIBUTOR

lfrah Dar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring