4

I'm using Hamcrest matchers to assert that a list of strings contains a string, ignoring the case. My code is as follows:

assertThat("myList has the string", myList, Matchers.hasItem(Matchers.equalToIgnoringCase(string)));

But my java compiler is complaining about this line:

cannot find symbol
[ERROR] symbol  : method assertThat(java.lang.String,java.util.List<java.lang.String>,org.hamcrest.Matcher<java.lang.Iterable<? super java.lang.Object>>)

Could anyone help me out with this error?

Thanks.

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
argo
  • 381
  • 1
  • 5
  • 15
  • I think `assertThat` only takes two parameters; you're passing three. – GriffeyDog Mar 02 '17 at 21:08
  • assertThat can take in a reason for failure as well. – argo Mar 02 '17 at 21:28
  • That line compiles for me. Which version of Java are you using? Which version of the Hamcrest and JUnit JARs are you using as well? (I'm using Java 8 update 122, hamcrest-all 1.3 and JUnit 4.12.) – Luke Woodward Mar 02 '17 at 22:29

3 Answers3

2

You can create your own matcher:

package com.melorriaga.movies.common;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

public class CaseInsensitiveSubstringMatcher extends TypeSafeMatcher<String> {

    private final String subString;

    private CaseInsensitiveSubstringMatcher(final String subString) {
        this.subString = subString;
    }

    @Override
    protected boolean matchesSafely(final String actualString) {
        return actualString.toLowerCase().contains(this.subString.toLowerCase());
    }

    @Override
    public void describeTo(final Description description) {
        description.appendText("containing substring \"" + this.subString + "\"");
    }

    @Factory
    public static Matcher<String> containsIgnoringCase(final String subString) {
        return new CaseInsensitiveSubstringMatcher(subString);
    }
}

Usage:

@Test
public void test() {
    List<String> myList = Arrays.asList("a", "b", "c");
    assertThat("myList has the string", myList, hasItem(containsIgnoringCase("b")));
}
Matias Elorriaga
  • 8,880
  • 5
  • 40
  • 58
2

Use equalToIgnoringCase:

assertThat("Has potential promotion", b2BCartPage.getPromotionTexts(), hasItem(equalToIgnoringCase(messages.getString("cart.promotion.attention"))));
Petar Tahchiev
  • 4,336
  • 4
  • 35
  • 48
1

Perhaps you will give assertj a try.

@Test
void containsIgnoreCase() {
    List<String> given = Arrays.asList("Alpha", "Beta");

    assertThat(given).anyMatch(s -> s.equalsIgnoreCase("alpha"));
    // if you favor method references over lamdas
    assertThat(given).anyMatch("alpha"::equalsIgnoreCase);
}

Big plus for assertj is that you can easily use code completion.

Frank Neblung
  • 3,047
  • 17
  • 34