【问题标题】:How to retrieve the method parameters of a mock-injected method, which is called by the function being tested?如何检索被测试的函数调用的模拟注入方法的方法参数?
【发布时间】:2020-05-05 13:05:32
【问题描述】:
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)。如何检索该参数?

【问题讨论】:

  • 如果可以使用它,我会注意到这种高级模拟交互是 Spock 框架使用起来更加简洁的案例之一。 Spock 是一种用 Groovy 编写的特定领域语言,它运行在 JUnit 之上,专门用于使编写 JUnit 测试更容易和更简单。

标签: java mockito junit4


【解决方案1】:

你正在测试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"));

【讨论】:

    【解决方案2】:
    when(mapvalues.get(any())).thenAnswer((Answer<String>) invocation -> {
        String key = invocation.getArgument(0);
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-04
    • 2023-04-10
    • 2018-06-06
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多