我正在使用Hamcrest匹配器断言字符串列表包含字符串,忽略大小写。我的代码如下:
assertThat("myList has the string", myList, Matchers.hasItem(Matchers.equalToIgnoringCase(string)));
但我的java编译器抱怨这一行:
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>>)
有人可以帮我解决这个错误吗?
感谢。
答案 0 :(得分:1)
使用equalToIgnoringCase
:
assertThat("Has potential promotion", b2BCartPage.getPromotionTexts(), hasItem(equalToIgnoringCase(messages.getString("cart.promotion.attention"))));
答案 1 :(得分:0)
您可以创建自己的匹配器:
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);
}
}
用法:
@Test
public void test() {
List<String> myList = Arrays.asList("a", "b", "c");
assertThat("myList has the string", myList, hasItem(containsIgnoringCase("b")));
}
答案 2 :(得分:0)
也许你会试试assertj。
I'm doing stuff for Foreground on thread 238....1
I'm doing stuff for Background on thread 459....1
I'm doing stuff for Background on thread 459....2
I'm doing stuff for Foreground on thread 238....2
I'm doing stuff for Foreground on thread 238....3
I'm doing stuff for Background on thread 459....3
I'm doing stuff for Background on thread 459....4
I'm doing stuff for Foreground on thread 238....4
Background will now throw an exception.
This was caught in the main thread: 'Object reference not set to an instance of an object.'
断言的大优点是你可以轻松使用代码完成。