java - 如何检索被测试的函数调用的模拟注入方法的方法参数?
问题描述
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"));
推荐阅读
- html - 如何将哈巴狗组件分解成块等
- java - 如何用 Java 制作一个肥皂客户端?
- android - 使用改造安卓上传文件?
- postgresql - PGAdmin4 在 Mac 中每天都无法启动:错误“无法联系应用程序服务器”
- wordpress - 2Checkout 授权自 6 月以来失败
- google-app-engine - 如何使部署到谷歌云应用引擎的应用程序可用于某些白名单 IP
- java - 将类的实例添加到 Arraylist
- mysql - 用 Where 删除。程序会删除所有内容。为什么?
- java - 如何知道自定义 Java 节点是否包含在第二个节点中?
- android - 在 Android 上监听连接变化