简体   繁体   English

用于StreamSupport的Junit测试案例

[英]Junit test cases for StreamSupport

I am new to test cases I tried several ways to write test case for below piece of code but I never succeeded. 我是测试用例的新手,我尝试了几种方法来为下面的代码编写测试用例,但从未成功。 How to write junit test case for below code using Powermockito? 如何使用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);

While, using a descent amount of mocks you can mock every single call, let me suggest you an alternative approach. 虽然使用大量模拟可以模拟每个调用,但我还是建议您使用另一种方法。

So you have a stream produced out of some input set ( irSet ) variable. 因此,您将有一些输入集( irSet )变量产生的流。 This stream makes "some" processing and returns an integer result. 此流进行“某些”处理并返回整数结果。

So if you "imagine" Its a black box: a kind of function that looks like this: 因此,如果您“想象”它的黑匣子:一种类似于以下的函数:

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

In this case, you might want to test what it does by supplying the various input sets and expecting for some outputs. 在这种情况下,您可能想要通过提供各种输入集并期望一些输出来测试其功能。 What if there are null -s in the input? 如果输入中有null -s怎么办? Will it fail or filter out what's needed. 它会失败还是过滤掉需要的东西。 What if the set is empty? 如果集合为空怎么办? What if there is SomeRow that really has STF_TY_GH data, what if the set doesn't have such a row? 如果有SomeRow确实具有STF_TY_GH数据怎么STF_TY_GH ,如果集合中没有这样的行怎么办?

Here is a test for example: 例如,这是一个测试:

  @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 
  }  

All-in-all, use mocks only for interactions (with something you can't really instantiate like DB API/remote HTTP calls) or for something that is not related to the tested code and is used as a dependency the tested code interacts with. 总之,仅将模拟用于交互(与您不能真正实例化的东西,如DB API /远程HTTP调用)或与测试的代码无关的东西,并用作与测试的代码进行交互的依赖项。 After all, the goal of unit tests is to test your code (the implementation of doSomething in this case and not to mock everything out). 毕竟,单元测试的目标是测试您的代码(在这种情况下, doSomething的实现而不是模拟一切)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM