在下面的示例中,可以检查表格的最后一个元素并没有真正出现,因为它已经在列表中。我如何检查预计将返回什么确切值?
public class streamExample2 {
public static void main(String[] args) {
List<String> stringList = new ArrayList<String>();
stringList.add("один");
stringList.add("два");
stringList.add("три");
stringList.add("один");
System.out.println (countstring(stringList));
}
public static List<String> countstring (List <String> stringList){
Stream <String> stream = stringList.stream ();
List<String>differentStrings = stream .distinct ()
.collect (Collectors.toList ());
return differentStrings;
}
}
您可以轻松地测试使用Junit返回值的方法。测试void main
更难,并且在较大的应用程序中没有任何意义(与包含main
的类别相比,那些具有更多类别的应用程序(。
在您的情况下,我将提取要测试的代码,例如:
:import java.util.List;
import java.util.stream.Collectors;
public class StackoverflowDemo {
public static List<String> getDistinctValuesFrom(List<String> list) {
return list.stream().distinct().collect(Collectors.toList());
}
}
由于此方法为static
,您不需要任何类的实例。
对于简单的单元测试 - 通常 - 您需要一个输入值和预期的输出值。在这种情况下,您可以实现两个列表,一个列表具有重复项,另一个代表消除第一个列表的重复项的预期结果。
JUNIT测试案例将预期输出与实际输出进行了比较。
junit使用比较(返回(值(方法(的特定方法。
测试此方法的测试类看起来像以下一种:
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import de.os.prodefacto.StackoverflowDemo;
class StreamTest {
@Test
void test() {
// provide a list that contains dpulicates (input value)
List<String> input = new ArrayList<String>();
input.add("AAA");
input.add("BBB");
input.add("CCC");
input.add("AAA");
input.add("DDD");
input.add("EEE");
input.add("AAA");
input.add("BBB");
input.add("FFF");
input.add("GGG");
// provide an expected result
List<String> expected = new ArrayList<String>();
expected.add("AAA");
expected.add("BBB");
expected.add("CCC");
expected.add("DDD");
expected.add("EEE");
expected.add("FFF");
expected.add("GGG");
// get the actual value of the (static) method with the input as argument
List<String> actual = StackoverflowDemo.getDistinctValuesFrom(input);
// assert the result of the test (here: equal)
assertEquals(expected, actual);
}
}
请注意,您也可以并且应该测试不希望的行为,例如误报或Exception
s。对于此简单示例以外的任何事情,Google用于Junit教程并阅读其中一些。
请注意,测试用例也可能是错误的,这可能会导致严重麻烦!仔细审查您的测试,因为预期值可能是错误的,因此尽管方法正确实施了测试失败的原因。
这可以通过哈希集完成。标签是一个仅存储唯一值的数据结构。
@Test
public void testSalutationMessage() {
List<String> stringList = new ArrayList<String>();
stringList.add("one");
stringList.add("two");
stringList.add("three");
stringList.add("one");
Set<String> set = new HashSet<String>();
stringList.stream().forEach(currentElement -> {
assertFalse("String already exist in List", set.contains(currentElement));
set.add(currentElement);
});
}