如何用Java中的新功能替换模拟功能

LiQ*_*eng 5 java mockito

我正在用Mockito编写UT,并且我想替换我的模拟函数(该数据库选择操作)

class DataBaseSelect {
    List<Long> selectDataFromDB(Long key){
         List<Long>  result  = db.select(key);
         return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

用我在Test类中编写的新功能(使用地图模拟数据库选择);

class MapSelect {
    List<Long> selectDataFromMap(Long key){
         List<Long> result = map.get(key);
         return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想用右键输入返回正确的值

我尝试使用ArgumentCaptor做到这一点,如下所示,但它没有按我的要求工作

ArgumentCaptor<Long> argumentCaptor = ArgumentCaptor.forClass(Long.class);
Mockito.when(dataBaseSelect.selectDataFromDB(argumentCaptor.capture())).thenReturn(MapSelect.selectDataFromMap(argumentCaptor.getValue()));
//some thing else here , 
Run Code Online (Sandbox Code Playgroud)

我想在调用dataBaseSelect.selectDataFromDB时进行模拟,然后从MapSelect.selectDataFromMap返回结果,并从dataBaseSelect.selectDataFromDB传递参数。

Esh*_*tIO 5

如果您需要替换自己的方法实现,您可以这样做:

// create method substitution
Answer<List<Long>> answer = invocation -> mapSelect.selectDataFromMap((Long) invocation.getArguments()[0]);

// Mock method
Mockito.doAnswer(answer).when(dataBaseSelect).selectDataFromDB(anyLong());
Run Code Online (Sandbox Code Playgroud)

您的解决方案不正确,因为捕获器旨在用于方法调用验证(调用方法的次数),例如:

// method calling: mockedObject.someMethod(new Person("John"));
//...
ArgumentCaptor<Person> capture = ArgumentCaptor.forClass(Person.class);
verify(mockedObject).someMethod(capture.capture());
Person expected = new Person("John");
assertEquals("John", capture.getValue().getName());
Run Code Online (Sandbox Code Playgroud)

在此示例中,预计“someMethod”被调用一次并返回人员“John”