jaxonjma
jaxonjma

Reputation: 307

How to get object value in void method SUT Mockito

i'm looking for a way to get the value of a List in my Test, i have this structure in my 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());
}

And i have a test with some like this:

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

But i don't know how see the 'List toSave' object, i tried with this:

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

But things like that don't work, any idea because the when run before the logic in my SUT and i tried with @Spy but it has the same problem

I did this too:

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

And in my test:

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

Upvotes: 0

Views: 957

Answers (3)

daniu
daniu

Reputation: 14999

In general, what you do is

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

Upvotes: 1

Marco Marchetti
Marco Marchetti

Reputation: 187

You can declare the List "toSave" outside of the method (declare it as a class variable, not as a method variable), and then use a getter to retrieve it.

Upvotes: 0

FredK
FredK

Reputation: 4084

Your toSave variable is declared local to the buys() method, so it disappears as soon as that method finishes. You should declare toSave as a private instance variable of the class that contains the buys() method, and then add a public getter to return that reference.

Upvotes: 0

Related Questions