断言集合中的每个字符串都包含一个子字符串的最佳方法?
Best Way to Assert That Each String in a Collection Contains a Substring?
断言字符串集合中的每个元素都包含特定子字符串的最佳方法是什么?
类似
List<String> list = Arrays.asList("xyfoobar", "foobarxy", "xyfoobarxy");
assertThat(list, eachElementContains("foobar")); // pass
像这样简单的东西:
list.forEach(string -> {
assertTrue(string.contains("foobar"));
});
这不使用 Hamcrest 匹配器,但具有相同的语义。
如果你使用 AssertJ:
import static org.assertj.core.api.Assertions.assertThat;
您可以执行以下操作:
List<String> list = Arrays.asList("xyfoobar", "foobarxy", "xyfoobarxy");
list.forEach(entry->assertThat(entry).describedAs("should contains 'foobar'").contains("foobar"));
我认为这会成功
List<String> result = list.stream() // convert list to stream
.filter(str ->str.indexOf("foobar")!=-1) // collects all "foobar" substring
.collect(Collectors.toList()); // collect the output and convert streams to a List
assertThat(list.equals(result)).isTrue();
一个简单的解决方案是使用 hamcrest 库。请尝试:
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.everyItem;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class MyTest {
@Test
public void test() {
List<String> list = Arrays.asList("xyfoobar", "foobarxy", "xyfoobarxy");
assertThat(list, (everyItem(containsString("foobar"))));
}
}
断言字符串集合中的每个元素都包含特定子字符串的最佳方法是什么?
类似
List<String> list = Arrays.asList("xyfoobar", "foobarxy", "xyfoobarxy");
assertThat(list, eachElementContains("foobar")); // pass
像这样简单的东西:
list.forEach(string -> {
assertTrue(string.contains("foobar"));
});
这不使用 Hamcrest 匹配器,但具有相同的语义。
如果你使用 AssertJ:
import static org.assertj.core.api.Assertions.assertThat;
您可以执行以下操作:
List<String> list = Arrays.asList("xyfoobar", "foobarxy", "xyfoobarxy");
list.forEach(entry->assertThat(entry).describedAs("should contains 'foobar'").contains("foobar"));
我认为这会成功
List<String> result = list.stream() // convert list to stream
.filter(str ->str.indexOf("foobar")!=-1) // collects all "foobar" substring
.collect(Collectors.toList()); // collect the output and convert streams to a List
assertThat(list.equals(result)).isTrue();
一个简单的解决方案是使用 hamcrest 库。请尝试:
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.everyItem;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class MyTest {
@Test
public void test() {
List<String> list = Arrays.asList("xyfoobar", "foobarxy", "xyfoobarxy");
assertThat(list, (everyItem(containsString("foobar"))));
}
}