Friday, 2 March 2018

Hamcrest: equalToIgnoringWhiteSpace: check equality of strings by ignoring case and white spaces

By using 'equalToIgnoringWhiteSpace' method, you can create a matcher of string that matches when the examined string is equal to the specified expected string, by ignoring case and whitespaces.

While matching the strings, below rules are applied.

         1. All leading and trailing whitespace of both the expectedString and the examined string are ignored
         2. Any remaining whitespace, appearing within either string, is collapsed to a single space before comparison
        
Ex
String str = "Hello World";
assertThat("comparing strings by ignoring case ", str, equalToIgnoringWhiteSpace("Hello       World"));

Find the below working application.

TestApp.java
package com.sample.model;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String str = "Hello World";

  assertThat("comparing strings by ignoring case ", str, equalToIgnoringWhiteSpace("Hello       World"));
  assertThat("comparing strings by ignoring case ", str, equalToIgnoringWhiteSpace("  Hello World "));
 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment