如何在void方法sut mockito中获取对象值



我正在寻找一种在测试中获取列表值的方法,我的SUT中有此结构:

.//... A run method with logic that call this:
 private void buys(){
     List<GroupLin> gruposByEarly = this.earlys.stream().map(this::agruparCompras).filter(Objects::nonNull).collect(Collectors.toList());
    List<MyClass> toSave = gruposByEarly.stream().flatMap(this::getToSave).map(this::valorar).collect(Collectors.toList());
    this.writer.persist(toSave.stream());
}

我有一个类似的测试:

@Test
public void runTest() {
 //...when sentences 
    super.cvlTask.run(getStepRequest());
 //...asserts
}

但是我不知道如何看"列表tosave"对象,我尝试了:

 when(entityWriter.persist(Mockito.any())).thenReturn(aMethodThatCallSUTGetMethodOfList);

但是类似的事情不起作用,任何想法,因为当我SUT中的逻辑之前运行时,我尝试了@Spy,但它具有相同的问题

我也这样做了:

private List<ValoracionLin> toSave;
//...logic
//... A run method with logic that call this:
 private void buys(){
     List<GroupLin> gruposByEarly = this.earlys.stream().map(this::agruparCompras).filter(Objects::nonNull).collect(Collectors.toList());
    this.toSave = gruposByEarly.stream().flatMap(this::getToSave).map(this::valorar).collect(Collectors.toList());
    this.writer.persist(toSave.stream());
}
public List<MyClass> getToSave(){
   return this.toSave;
}

在我的测试中:

 when(entityWriter.persist(Mockito.any())) 
.thenReturn(getValoracionesResultadoSUT());
 private Integer getValoracionesResultadoSUT() {
       this.valoracionesResultado = this.cvlTask.getToSave();
       if(null!=this.valoracionesResultado)
       return this.valoracionesResultado.size();
       else 
       return 0;
  }

通常,您要做的是

@Mock Writer writer;
@InjectMock MyService sut;
@Captor ArgumentCaptor<List<Data>> captor;
@Test
public void testSave() {
    List<InputData> input = ...
    sut.callMethod(input);
    // check that write() was called on the writer
    verify(writer).write(captor.capture());
    // retrieve the value it was called with
    List<Data> saved = captor.getValue();
    // do some more validation on the data if necessary
}

您的 toSave变量被声明为buys()方法本地,因此该方法完成后立即消失。您应该将toSave声明为包含buys()方法的类的私人实例变量,然后添加一个public Getter返回该参考。

您可以在方法之外声明列表" tosave"(将其声明为类变量,而不是方法变量),然后使用getter检索。

相关内容

  • 没有找到相关文章

最新更新