Wednesday, 4 April 2018

Hamcrest: hasKey: Check for the existence of key

By using 'haskey method, you can create a matcher for Maps to match when the examined Map contains at least one key that is equal to the specified key.

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 the key 'I346'",employeeMap, hasKey("I346"));

TestApp.java
package com.sample.tests;

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

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

import org.junit.Test;

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 the key 'I346'",employeeMap, hasKey("I346"));
  
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment