Saturday 30 June 2018

Junit: Assert by matcher

Junit provides below methods to match the object with given matcher. Junit uses hamcrest library to perform comparison operations using matchers.

public static <T> void assertThat(T actual, Matcher<? super T> matcher)
Asserts that 'actual' satisfies the condition specified by matcher. If 'actual' is not satisifes the condition specified by matcher, then junit throws an assertion error without message.
          
public static <T> void assertThat(String reason, T actual, Matcher<? super T> matcher)
Asserts that 'actual' satisfies the condition specified by matcher. If 'actual' is not satisifes the condition specified by matcher, then junit throws an assertion error with message.

If you are interested in learning hamcrest, I would recommend you to go through my below tutorial series.

Example
String name = "Hello World";
assertThat(name, both(startsWith("Hello")).and(containsString("rld")));

Above example pass the test case, if the string ‘name’ starts with ‘Hello’ and contains the string ‘rld’.

Find the below working application.

DemoTestApp.java
package com.sample.arithmetic;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.both;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.everyItem;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;

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

import org.junit.Test;

public class DemoTestApp {

 @Test
 public void testAssertThatStringContainsBoth() {
  String name = "Hello World";
  assertThat(name, both(startsWith("Hello")).and(containsString("rld")));
 }

 @Test
 public void testAssertThatEitherOfString() {
  String name = "Hello World";
  assertThat(name, either(startsWith("Hello")).or(containsString("abrakadabra")));
 }

 @Test
 public void testAssertThatMatchAny() {
  String name = "Hello World";
  assertThat(name, anyOf(startsWith("Hello"), containsString("abrakadabra")));
 }

 @Test
 public void testAssertThatMatchEveryItem() {
  List<String> strs = Arrays.asList("men", "met", "melt");
  assertThat("elements shoudl start with me", strs, everyItem(startsWith("me")));
 }

 @Test
 public void testAssertThatHasItems() {
  List<String> strs = Arrays.asList("men", "met", "melt");
  assertThat("strs must have 'melt' and 'men'", strs, hasItems("melt", "men"));
 }

 @Test
 public void testAssertThatAllOf() {
  String name = "Hello World";

  assertThat(name, allOf(startsWith("Hello"), containsString("rld"), endsWith("World")));
 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment