代码如下所示。我希望它测试keyNames的所有元素。 但是,如果任何测试失败并且不会遍历所有数组元素,它将停止。 我的理解是,assertAll中的所有断言均已执行,所有失败都应一起报告。
感谢您的时间和帮助。
private void validateData(SearchHit searchResult, String [] line){
for(Integer key : keyNames){
String expectedValue = getExpectedValue(line, key);
String elementName = mappingProperties.getProperty(key.toString());
if (elementName != null && elementName.contains(HEADER)){
assertAll(
() -> assumingThat((expectedValue != null && expectedValue.length() > 0),
() -> {
String actualValue = testHelper.getHeaderData(searchResult, elementName);
if(expectedValue != null) {
assertEquals(expectedValue, actualValue, " ###Element Name -> " + elementName +" : Excepted Value ### " + expectedValue + " ### Actual Value ###" + actualValue);
}
}
)
);
}
}
}
答案 0 :(得分:1)
assertAll()
对传递给assertAll()
的调用的所有声明和错误进行分组。它不会对在测试方法期间发生的所有调用进行断言分组。
在您发布的代码中,您将一个断言lambda传递到assertAll()
中。由于每个key
都有一个单独的assertAll()
调用,因此不会对多个键进行错误分组。
要确保分别测试集合中的所有值,请查看parameterized tests。
答案 1 :(得分:0)
Assertions.assertAll()
的Javadoc指出:
声明所有提供的可执行文件都不会引发异常。
实际上,您在每次迭代时都在Executable
中提供了一个assertAll()
。
因此,循环的任何迭代失败都会终止测试执行。
实际上,您每次都最多请求一个断言来多次调用assertAll()
:
if(expectedValue != null) {
assertEquals(expectedValue, actualValue, " ###Element Name -> " + elementName +" : Excepted Value ### " + expectedValue + " ### Actual Value ###" + actualValue);
}
您想要做的是相反的操作:通过传递执行所需断言的多个assertAll()
实例来调用Executable
。
因此,您可以将它们收集在具有经典循环的List
中,并以这种方式传递它:
assertAll(list.stream())
或创建Stream<Executable>
而不进行任何收集并将其直接传递给assertAll(stream)
。
这里是带有Stream的版本(根本没有经过测试),但是您应该了解一下:
Stream<Executable> executables =
keyNames.stream()
.map(key->
// create an executable for each value of the streamed list
()-> {
String expectedValue = getExpectedValue(line, key);
String elementName = mappingProperties.getProperty(key.toString());
if (elementName != null && elementName.contains(HEADER)){
assumingThat((expectedValue != null && expectedValue.length() > 0),
() -> {
String actualValue = testHelper.getHeaderData(searchResult, elementName);
if(expectedValue != null) {
assertEquals(expectedValue, actualValue, " ###Element Name -> " + elementName +" : Excepted Value ### " + expectedValue + " ### Actual Value ###" + actualValue);
}
}
);
}
}
);
Assertions.assertAll(executables);
答案 2 :(得分:0)
如@ {user31601所示,参数化测试(请参阅documentation)自动独立地测试所有情况。
这将导致以下(稍微简单一些)代码):
@ParameterizedTest
@MethodSource("getKeys")
void testKey(String key) {
String elementName = mappingProperties.getProperty(key.toString());
assumeTrue(elementName != null);
assumeTrue(elementName.contains(HEADER));
String expectedValue = getExpectedValue(line, key);
assumeTrue(expectedValue != null);
assumeTrue(expectedValue.length() > 0);
String actualValue = testHelper.getHeaderData(searchResult, elementName);
String doc = String.format("name: %s, expected %s, actual %s", elementName, expectedValue, actualValue);
assertEquals(expectedValue, actualValue, doc);
}
private static Stream<String> getKeys() {
return keyNames.stream()
}