Wednesday 4 April 2018

Hamcrest: hasEntry: Check for the entry in map

public static <K, V> org.hamcrest.Matcher<java.util.Map<? extends K, ? extends V>> hasEntry(org.hamcrest.Matcher<? super K> keyMatcher, org.hamcrest.Matcher<? super V> valueMatcher)
By using ‘hasEntry’ method, you can create a matcher for Maps to match when the examined Map contains at least one entry whose key satisfies the specified keyMatcher and whose value satisfies the specified valueMatcher.

Ex
Map<String, String> employeeMap = new HashMap<>();
                 
employeeMap.put("I1234", "Krishna Gurram");
employeeMap.put("I346", "Chamu M");
employeeMap.put("I546", "Sri Ram");
                 
assertThat("employeeMap must contain <I346, Chamu M>",employeeMap, hasEntry(equalTo("I346"), equalTo("Chamu M")));

Find the below working application.

TestApp.java
package com.sample.tests;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.equalTo;

public class TestApp {

 @Test
 public void testmethod() {
  Map<String, String> employeeMap = new HashMap<>();
  
  employeeMap.put("I1234", "Krishna Gurram");
  employeeMap.put("I346", "Chamu M");
  employeeMap.put("I546", "Sri Ram");
  
  assertThat("employeeMap must contain <I346, Chamu M>",employeeMap, hasEntry(equalTo("I346"), equalTo("Chamu M")));
  
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment