Noob
Noob

Reputation: 27

Write a mockito test for void method

I am trying to write a test case for a method which is very badly written, below is implementation of the method:

public void processData(){
 DB.connectToDB1();
 List rawData = DB.getRawData();
 List processedData = new List(); 
 for (Object obj : rawData){
  //pass through filter
  if(obj.passesFilter){
   processedData.add(obj);
  }
 }
 DB.connectToDB2();
 DB.insertProcessedData(processedData);
}

I want to test if filter rules are working correctly, what approach should i take?

Upvotes: 0

Views: 1112

Answers (1)

Georg Leber
Georg Leber

Reputation: 3605

You should mock DB and on getRawData() return the list of data, you want to be processed:

Mockito.when(DB.getRawData()).thenReturn(myList);

And then use Mockito.verify to check that all of the rawData that should pass the filter is in the list of processedData, by using a Captor, which can capture the the data passed to insertProcessedData:

@Captor
ArgumentCaptor<String> listCaptor;

Mockit.verify(DB).insertProcessedData(listCaptor.capture());
List<Object> processedData = listCaptor.getValue();

And then you can check processedData for whatever you need (e.g. expected size,...).

Upvotes: 1

Related Questions