Tuesday 27 February 2018

Hamcrest: notNullValue : Creates a matcher that matches if examined object is not null

notNullValue creates a matcher that matches if examined object is not null. It is shortcut to not(nullValue()).

For example, below statement makes the testcase pass, if the firstName of the employee is not null
assertThat("firstName property of emp should not be to null", emp.getFirstName(), notNullValue());

Find the below working application.

Employee.java
package com.sample.model;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;

 public Employee() {

 }

 public int getId() {
  return id;
 }

 public String getFirstName() {
  return firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setId(int id) {
  this.id = id;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

}

EmployeeTest.java

package com.sample.model;

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

import org.junit.Test;

public class EmployeeTest {

 @Test
 public void employeeConstructor_properInput_firstNameAndLastNameInUpper() {
  Employee emp = new Employee();
  emp.setId(1);
  emp.setFirstName("Krishna");
  emp.setLastName("Gurram");

  assertThat("id property of emp should be set to null", emp.getId(), equalTo(1));
  assertThat("firstName property of emp should not be set to null", emp.getFirstName(), notNullValue());
  assertThat("lastName property of emp should not be set to null", emp.getLastName(), notNullValue());

 }
}

notNullValue() also provides other overloaded method to facilitate the type inference.
public static <T> org.hamcrest.Matcher<T> notNullValue(java.lang.Class<T> type)

Ex
assertThat("firstName property of emp should be set to null", emp.getFirstName(), notNullValue(String.class));


EmployeeTest.java

package com.sample.model;

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

import org.junit.Test;

public class EmployeeTest {

 @Test
 public void employeeConstructor_properInput_firstNameAndLastNameInUpper() {
  Employee emp = new Employee();
  emp.setId(1);
  emp.setFirstName("Krishna");
  emp.setLastName("Gurram");

  assertThat("id property of emp should be set to null", emp.getId(), equalTo(1));
  assertThat("firstName property of emp should not be set to null", emp.getFirstName(), notNullValue(String.class));
  assertThat("lastName property of emp should not be set to null", emp.getLastName(), notNullValue(String.class));

 }
}


Previous                                                 Next                                                 Home

No comments:

Post a Comment