如何检索被测试函数调用的模拟注入方法的方法参数?
How to retrieve the method parameters of a mock-injected method, which is called by the function being tested?
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)方法,其中returns一个整数值,但是我想把key值传给map.get(key ) 调用方法时。我如何检索该参数?
when(mapvalues.get(any())).thenAnswer((Answer<String>) invocation -> {
String key = invocation.getArgument(0);
});
您正在测试 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"));
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)方法,其中returns一个整数值,但是我想把key值传给map.get(key ) 调用方法时。我如何检索该参数?
when(mapvalues.get(any())).thenAnswer((Answer<String>) invocation -> {
String key = invocation.getArgument(0);
});
您正在测试 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"));