top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-
Writer's picturegeeta.thakur2008

Hamcrest Assertion

In this blog we will learn and understand about What is Hamcrest and How to use it?


The Hamcrest is a popular framework that helps us to create the Matcher Objects

The Hamcrest is well-known assertion used along with the Java Programming Language.Hamcrest can implement in a number of other languages too, example Php, Python, Ruby, c# etc.....

The Hamcrest is known as an assertion library and widely used framework for unit testing along with JUnit in Java world for making assertions

The Hamcrest framework is also used with the mocking frameworks such as JMock, EasyMock and Mockito

The Hamcrest is used for writing matchers objects allowing match rules to be defined declarative style rather than a procedural style

This uses matcher classes for making an assertion

To use the Hamcrest matchers in your test you use the assertThat statement followed by one or several matchers.

We can use this the Hamcrest after we import it into our file. Once, we import the Hamcrest if we specify the static it will be easy in calling this method and also it will reduces the code


How to import Hamcrest Jar File?

We need to import org.hamcrest. library

If we add static to this we can import all Hamcrest Matchers methods in this way, this is also makes it easier to find the matchers through code completion.


Example of importing the Hamcrest Matchers below by adding static and adding " * " at the end.





Advantages of using the Hamcrest:


It’s readable and in the plain English

The code is neat and intuitive

It shows fluent error messages when the assertion fails and give more information on the failure

Provides thin methods like “is” and “not”, also called decorators, for more readability

The Compile time errors — rather than the run time errors

Flexibility with writing the test conditions

Portable — if you are using the hamcrest — you can use jUnit or TestNG as the underlying framework.


Matchers in Testing:

Matchers check given object is equal or not.

Given object null or not null.

Test if object is the exact same instance as another.

In some situations where matchers are invaluable such as UI validation or data filtering but it is in the area of writing flexible tests that matchers are most commonly used

Hamcrest Vs TestNG:

TestNG is a testing framework and Hamcrest is a Matchers framework and both frameworks do assertions but Hamcrest do better job

Hamcrest is readability

Descriptive error messages ( In hamcrest, whenever there is an assertion failure, the hamcrest will display the cause of failure and it will output the expected and the actual results. The TestNG will not provide this information)

Type Safety ( Ex: In the hamcrest, if you try to match an integer with a string, you will get an error during compile time itself . TestNg will not provide this information )


The different ways of Hamcrest Matchers used according to various scenarios like Collection Matchers, Numbers Matchers and String Matchers. Below are the list of Hamcrest Matchers


Collection matchers (List, Array, Map, etc.)


1.hasItem() -> check a single element in a collection

2.not(hasItem()) -> check single element is NOT in a collection

3.hasItems() -> Check all elements are in a collection

4.contains() -> Check all elements are in a collection and a strict order

5.containsInAnyOrder() -> Check all elements are in a collection and any order

6.empty() -> Check if the collection is empty

7.not(emptyArray()) -> Check if the Array is not empty

8.hasSize() -> Check the size of a collection

9.everyItem(startsWith()) -> Check if every item in a collection starts with a specified string

10.hasKey() -> Map -> Check if Map has the specified key [value is not checked]

11.hasValue() -> Map -> Check if Map has at least one key matching the specified value

12.hasEntry() -> Maps -> Check if Map has the specified key-value pair

13.equalTo(Collections.EMPTY_MAP) -> Maps [Check if empty]

14.allOf() -> Matches if all matchers matches

15.anyOf() -> Matches if any of the matchers matches


Numbers:


1.greaterThanOrEqualTo()

2.lessThan()

3.lessThanOrEqualTo()


String:


1.containsString()

2.emptyString()


Note: While we are executing the code in the selenium to use this hamcrest we need to import the hamcrest library, if we use a static modifier in hamcrest import while writing the code we don’t need to use Matchers. we can call the method and execute easily as well the code also be reduced.

The usage of Hamcrest Matchers is demonstrated by the following code snippet.


More Examples using Hamcrest Matchers:


package com.rest;

import static io.restassured.RestAssured.given;

import static org.hamcrest.Matchers.hasItems;

import static org.hamcrest.Matchers.equalTo;

import static org.hamcrest.Matchers.is;

import static org.hamcrest.MatcherAssert.assertThat;

import org.testng.annotations.Test;

import io.restassured.path.json.JsonPath;

import io.restassured.response.Response;


public class HamcrestAssert{

@Test

public void hamcrest_assert_on_extracted_response() {

String name = given().

baseUri(“https://api.getpostman.com").

header(“X-Api-Key”,”PMAK-62dd3be1f2197b673bb9313e-311678da8c49f1b5d28f37e348b64fd6ee”).

when().

get(“/collections”).

then().

assertThat().

statusCode(200).

extract().

response().path(“collections[0].name”);

System.out.println(“Collection Name :” +name);

assertThat(name,equalTo(“Employee Controller”)); // hamcrest assertion

//Assert.assertEquals(name,”Employee Controller”); // testNg assertion

}


@Test

public void hamcrest_assert_on_extracted_response1(){

//contains method

given().

baseUri(“https://api.getpostman.com").

header(“X-Api-Key”,”PMAK-62dd3be1f2197b673bb9313e-311678da8c49f1b5d28f37e348b64fd6ee”).

when().

get(“/collections”).

then().

assertThat().

statusCode(200).

body(“collections.name”,contains(“Employee Controller”,”New Collection”, “New Collection”,”Git_Api_Suite”,”rmgyantra2", “testCaseAssignment”)

);

}


@Test

public void hamcrest_assert_on_extracted_response2(){

given().

baseUri(“https://api.getpostman.com").

header(“X-Api-Key”,”PMAK-62dd3be1f2197b673bb9313e-311678da8c49f1b5d28f37e348b64fd6ee”).

when().

get(“/collections”).

then().

assertThat().

statusCode(200).

body(“collections.name”,containsInAnyOrder(“Employee Controller”,”New Collection”, “New Collection”,”Git_Api_Suite”,”rmgyantra2", “testCaseAssignment”),

“collections.name”,is(not(emptyArray())), “collections.name”,hasSize(6),

“collections.name”, allOf(startsWith(“Employee”), containsString(“”))

);

}

}


We conclude this by:

Hamcrest comes bundled with lots of useful matchers, but you’ll probably find that you need to create your own from time to time to fit your testing needs.

By writing our own matcher we’ll eliminate code duplication and make tests more readable.

While executing the test we get any errors in the programme, it will print the actual and expected errors in the console which help us to identify the actual cause for the test failure.

Hamcrest target is to make your tests easier to write and read.


I hope that this blog helped you to understand what Hamcrest Assertion is !!


Thank you!!!


Hope you liked it !!


Happy coding :)



334 views0 comments

Recent Posts

See All

Comentarios

Obtuvo 0 de 5 estrellas.
Aún no hay calificaciones

Agrega una calificación
bottom of page