Friday 23 March 2018

Hamcrest: hasItem: Check for the existence of at least one item

By using 'hasItem' method, you can create a matcher, for Iterables (Collections that implements Iterable interface) that is used to check whether given collection has at least one item that matches to the specific matcher or not.

a. Check the collection, whether it has atleast one element that is > 40.
List<Integer> employeeAges = Arrays.asList(24, 45, 32);
assertThat("Age must be > 20", employeeAges, hasItem(greaterThan(40)));

b. Check whether collection of strings has atleast one element that ends with "et" ot not.
List<String> strs = Arrays.asList("men", "met", "melt");
assertThat("elements should start with me", strs, hasItem(endsWith("et")));

Find the below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItem;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  List<Integer> employeeAges = Arrays.asList(24, 45, 32);
  assertThat("Age must be > 20", employeeAges, hasItem(greaterThan(40)));

  List<String> strs = Arrays.asList("men", "met", "melt");
  assertThat("elements shoudl start with me", strs, hasItem(endsWith("et")));
 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment