Tuesday 6 March 2018

Hamcrest: array: Match every element of array with specific matcher

By using 'array' matcher, you can create a matcher that matches array whose elements are satisfied by the specified matchers.

For ex
Integer[] primes = { 2, 3, 5, 7 };
assertThat("Checking first 4 primes", primes, array(equalTo(2), equalTo(3), equalTo(5), equalTo(7)));

Make sure that the number of matchers are equal to number of elements in the array.

Find the below working applicaiton.

TestApp.java

package com.sample.tests;

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

import org.junit.Test;

public class TestApp {

 @SuppressWarnings("unchecked")
 @Test
 public void testmethod() {
  String[] empIds = { "I312", "I768", "I456" };
  assertThat("Checking empIds details", empIds, array(equalTo("I312"), equalTo("I768"), equalTo("I456")));

  Integer[] primes = { 2, 3, 5, 7 };
  assertThat("Checking first 4 primes", primes, array(equalTo(2), equalTo(3), equalTo(5), equalTo(7)));

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment