如何检索模拟注入的方法的方法参数,该方法被被测试的函数调用?

问题描述 投票:1回答:2
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)。我如何检索该参数?

java mockito junit4
2个回答
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"));

0
投票
when(mapvalues.get(any())).thenAnswer((Answer<String>) invocation -> {
    String key = invocation.getArgument(0);
});
© www.soinside.com 2019 - 2024. All rights reserved.