gpt4 book ai didi

java - StreamSupport 的 Junit 测试用例

转载 作者:行者123 更新时间:2023-12-01 19:32:54 25 4
gpt4 key购买 nike

我是测试用例的新手,我尝试了多种方法为下面的代码编写测试用例,但从未成功。如何使用Powermockito为下面的代码编写junit测试用例?

StreamSupport.stream(irSet.spliterator(), false)
.filter(iResultRow -> iResultRow !=null)
.mapToInt(iResultRow ->{
String event = iResultRow.get("STF_TY_GH");
return StringUtils.isNotBlank(event) ? Integer.parseInt(event) : 1;
}).findFirst().orElse(1);

最佳答案

虽然使用一定量的模拟可以模拟每个调用,但我建议您使用另一种方法。

因此,您有一个由某些输入集 (irSet) 变量生成的流。该流进行“一些”处理并返回一个整数结果。

所以如果你“想象”它是一个黑盒子:一种看起来像这样的函数:

int doSomething(Set<SomeRow> irSet) {
... your implementation is here...
}

在这种情况下,您可能希望通过提供各种输入集并期望一些输出来测试它的功能。如果输入中有 null-s 怎么办?它会失败还是过滤掉需要的东西?如果集合为空怎么办?如果有 SomeRow 确实有 STF_TY_GH 数据怎么办,如果集合中没有这样的行怎么办?

以下是一个测试示例:

  @Test
public void test_rows_with_null_are_processed_correctly() {

// setup:
Set<SomeRow> input = ...// prepare a set with null values

// when:
Integer actual = underTest.doSomething(input)

// then:
// verify this "actual" whether it should be 1 or something else
}

总而言之,仅将模拟用于交互(与您无法真正实例化的东西,如 DB API/远程 HTTP 调用)或与测试代码不相关并用作测试依赖项的东西代码交互。毕竟,单元测试的目标是测试您的代码(在本例中是 doSomething 的实现,而不是模拟所有内容)。

关于java - StreamSupport 的 Junit 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59025599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com