Hamcrest

Hamcrest

Hello Everyone,

Here is small concept of hamcrest, Where to use, what's the purpose, Hamcrest Vs TestNG, Advantages. I explained this concept through example.Very easy to understand. Have a look...

We have to add dependency in our pom.xml file

<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest-library -->

<dependency>

??<groupId>org.hamcrest</groupId>

??<artifactId>hamcrest-library</artifactId>

??<version>1.3</version>

??<scope>test</scope>

</dependency>


HAMCREST ASSERTION

======================

-> Hamcrest is a well known assertion library used for unit testing along with JUnit.

-> Hamcrest can be used along with Rest Assured for assertions.

-> Uses matcher classes for making assertions


Adv:

=====

-> Human readable and in plain english

-> Code is neat and intuitive

-> Provides thin methods like "is" and "not", also called as decorators, for more readibility


Hamcrest Vs TestNG

====================

-> Readibility

-> Descriptive error messages ( When ever there is an assertion failure ,the hamcrest will display the cause of? failure and it will output the expected and the actual results. TestNg will not provide this info)

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


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

==============================================

hasItem() -> check single element in a collection

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

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

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

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

empty() -> Check if collection is empty

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

hasSize() -> Check size of a collection

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


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

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

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

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

allOf() -> Matches if all matchers matches

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


Numbers:

greaterThanOrEqualTo()

lessThan()

lessThanOrEqualTo()


String:

containsString()

emptyString()



Examples :

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(""))

????);

?}

}

I hope you got clarity on hamcrest assertions, how to use...All the best!

Do more practice on...


Thank You!

Published By: Shruti Kuratkar

Date: Sun,19 Feb 2023

要查看或添加评论,请登录

Shruti Kuratkar的更多文章

  • Who Will Cry When You Die

    Who Will Cry When You Die

    Who Will Cry When You Die by Robin Sharma gives you simple and actionable tips, which you can use to improve the…

  • Who Will Cry When You Die

    Who Will Cry When You Die

    This book is a mini life-training package. You should read this book at least once.

    4 条评论
  • Who Will Cry When You Die!

    Who Will Cry When You Die!

    In this article Who Will Cry When You Die book summary, I’ll share 27 incredible lessons to lead you to a more abundant…

  • Difference between Webservice and API

    Difference between Webservice and API

    Hi Everyone, Here I am sharing one of important concept /question which is asking in every api testing interview . I…

    1 条评论
  • Subconscious Mind and Habit

    Subconscious Mind and Habit

    Hello, Subconscious mind is a vital part of our mind. It is more powerful.

  • Logging In Rest assured!

    Logging In Rest assured!

    Hello, In this blog we will learn about lagging in rest Assured. Logging and different type of logging.

  • What is holding us back?

    What is holding us back?

    Hello everyone, Good to see you..

    1 条评论
  • RequestSpecification

    RequestSpecification

    Introduction Have you worked on testing some APIs? Or have you used multiple test cases with some common configurations…

    1 条评论
  • Self-Esteem

    Self-Esteem

    Hello everyone, In this blog I mentored about self-esteem, If we have low self-esteem, what will happen, how to…

  • Winning Strategies

    Winning Strategies

    Hi everyone, Being a self-help book lover, recently I am reading this an amazing book You Can Win written by an Indian…

社区洞察

其他会员也浏览了