Wednesday, 21 February 2018

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

'nullValue' creates a matcher that matches if the examined object is null.

For example,
assertThat("firstName property of emp should be set to null", emp.getFirstName(), nullValue());

Above statement checks whether employee firstName is null or not.

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 org.junit.Test;

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

public class EmployeeTest {

 @Test
 public void employeeConstructor_properInput_firstNameAndLastNameInUpper() {
  Employee emp = new Employee();

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

 }
}

'nullValue' provides other overloaded method, where you can facilitate type inference.
public static <T> org.hamcrest.Matcher<T> nullValue(java.lang.Class<T> type)


EmployeeTest.java

package com.sample.model;

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

import org.junit.Test;

public class EmployeeTest {

 @Test
 public void employeeConstructor_properInput_firstNameAndLastNameInUpper() {
  Employee emp = new Employee();

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

  Employee emp2 = null;
  assertThat("emp2 should be null", emp2, nullValue(Employee.class));

 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment