Monday, 19 March 2018

Hamcrest: instanceOf: Check whether object is instance of class or not

By using instanceOf method, you can create a matcher that matches when the examined object is an instance of the specified type.

Ex
assertThat("str should be of type String", str, instanceOf(String.class));
assertThat("intVar should be of type Integer", intVar, instanceOf(Integer.class));
assertThat("bigInt should be of type BigInteger", bigInt, instanceOf(BigInteger.class));

Find the below working application.

TestApp.java

package com.sample.tests;

import java.math.BigInteger;

import org.junit.Test;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

public class TestApp {

 @Test
 public void testmethod() {
  String str = new String("Hello World");
  Integer intVar = 10;
  BigInteger bigInt = new BigInteger("1234");

  assertThat("str should be of type String", str, instanceOf(String.class));
  assertThat("intVar should be of type Integer", intVar, instanceOf(Integer.class));
  assertThat("bigInt should be of type BigInteger", bigInt, instanceOf(BigInteger.class));

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment