Wednesday 7 March 2018

hamcrest: hasItemInArray: Check the existence of item in the array

'hasItemInArray' is used to check the existance of item in the array.

It is available in two overloaded forms.

public static <T> org.hamcrest.Matcher<T[]> hasItemInArray(T element)
This method creates a matcher that is used to check whether the array has given element or not.

Ex
String[] empIds = { "I312", "I768", "I456" };
assertThat("empIds must have 'I768'", empIds, hasItemInArray("I768"));

Find the below working application.

TestApp.java
package com.sample.tests;

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

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String[] empIds = { "I312", "I768", "I456" };
  assertThat("empIds must have 'I768'", empIds, hasItemInArray("I768"));

  Integer[] primes = { 2, 3, 5, 7 };
  assertThat("empIds must have 5", primes, hasItemInArray(5));
 }
}

public static <T> org.hamcrest.Matcher<T[]> hasItemInArray(org.hamcrest.Matcher<? super T> elementMatcher)
You can create a matcher for arrays that matches when the examined array contains at least one item that is matched by the specified elementMatcher.

Ex
String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
assertThat("Any one of the names must starts with 'Ch'", names, hasItemInArray(startsWith("Ch")));

Find below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItemInArray;
import static org.hamcrest.Matchers.startsWith;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
  assertThat("Any one of the names must starts with 'Ch'", names, hasItemInArray(startsWith("Ch")));

 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment