public class SearchServiceTest
{
@InjectMocks
SearchService searchService;
@Mock
Mapvalues mapvalues;
@Before
public void setUp() throws FileNotFoundException
{
MockitoAnnotations.initMocks(this);
Map<String, Integer> map = new Hashmap<>();
File fp = ResourceUtils.getFile("classpath:test.txt");
Scanner sc = new Scanner(fp);
while (sc.hasNextLine())
{
String line = sc.nextLine();
map.put(line, 300);
}
}
@Test
public void testDoSomething()
{
searchService.doSomething();
//so basically this doSomething() method calls the method mapvalues.getval(String key),
//but instead I want to perform map.get(key) when the method is called.
}
}
所以doSomething()方法调用mapvalues.getval(String key)方法,该方法返回一个整数值,但我想在调用该方法时,将key值传给map.get(key)。我如何检索该参数?
你正在测试 searchService.doSomething();
我将假设这个方法的主体包含以下语句 mapvalues.getval("KEY-VALUE");
在进行测试调用之前,在你的设置中,将你期望被调用的方法存根化为
when(mapvalues.getval(any())).then(new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
return map.get(invocation.getArgument(0, String.class));
}
});
在测试调用之后,你要确保想要的方法已经被调用,并获得了预期的参数值。
verify(mapvalues).getval(eq("KEY-VALUE"));
when(mapvalues.get(any())).thenAnswer((Answer<String>) invocation -> {
String key = invocation.getArgument(0);
});