【问题标题】:PowerMockito how to capture a parameter passed to a mock object?PowerMockito 如何捕获传递给模拟对象的参数?
【发布时间】:2018-03-07 11:17:43
【问题描述】:

我正在尝试使用 PowerMockito 捕获在输入中传递给模拟对象的参数,代码如下:

//I create a mock object
ClassMocked mock = PowerMockito.mock(ClassMocked.class);

//Create the captor that will capture the String passed in input to the mock object
ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);

//When the method put is executed on my mock I want the second parameter (that is a String) to be captured
Mockito.verify(mock).put(anyString(), inputDataMapCaptor.capture());

//Creates the instance of the class that I want to test passing the mock as parameter
ClassToTest instance = new ClassToTest(mock);

//Executes the method that I want to test
instance.methodToTest();

/* I know that during the execution of "methodToTest()" mock.put(String,String) will be executed and I want to get the second string parameter. */

当我执行测试时,执行 Mockito.verify(mock).put(...); 行时出现异常

"想要但未调用 mock.put(any,Capturing argument);"

怎么了?

【问题讨论】:

    标签: java unit-testing junit mockito powermockito


    【解决方案1】:

    你应该在Mockito.verify(mock).put(anyString(), inputDataMapCaptor.capture());之前调用instance.methodToTest();

    【讨论】:

    • 是的,你是对的,我把验证放在后面,它可以工作,但我想念它是如何工作的。如果我将验证放在测试执行的方法之后,模拟如何知道它必须捕获参数?
    • 我不确定 PowerMockito 的内部结构,但它应该记录所有对 mock 方法的调用及其参数
    【解决方案2】:

    verify() 验证指定的方法调用确实发生了。

    您无法“预先”验证方法调用应该发生。

    因此:verify() 需要发生在事实之后,而不是之前!

    【讨论】:

    • 您的回答是正确的,我接受了用户 chomnoue 的回答,因为他首先回答了。
    猜你喜欢
    • 2023-03-09
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多