简体   繁体   English

为void方法编写一个模拟测试

[英]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? 我想测试过滤器规则是否正常工作,应该采取哪种方法?

You should mock DB and on getRawData() return the list of data, you want to be processed: 您应该模拟DB并在getRawData()返回要处理的数据列表:

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 : 然后使用Mockito.verify检查所有的RAWDATA的应通过过滤器在列表中processedData ,通过使用Captor ,它可以捕捉传递给数据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 (eg expected size,...). 然后,您可以检查processedData是否需要任何内容​​(例如,预期大小等)。

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

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