在下面的示例中,可以检查工作表的最后一个元素是否真正出现,因为它已经在列表中。如何检查预计返回的确切值?
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());
}
}
由于此方法是静态
,因此您不需要任何类的实例。
对于简单的单元测试(通常),您需要一个输入值和一个预期输出值。在这种情况下,您可以实现两个列表,一个包含重复项,另一个表示消除第一个列表的重复项的预期结果。
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);
}
}
请注意,您也可以而且应该测试不良行为,例如误报或异常
。对于比这个简单示例更进一步的内容,请在 google 上搜索 JUnit 教程并阅读其中的一些内容。
Note that test cases may be wrong, too, which may cause serious trouble! Review your tests carefully because expected values may be wrong and thus a reason for test failing though the methods are correctly implemented.
关于java - 如何在 JUnit 中检查我们期望返回的确切值是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56110973/