【问题标题】:PowerMock - How to call manipulate the parameters of a mocked methodPowerMock - 如何调用操纵模拟方法的参数
【发布时间】:2015-06-30 03:40:52
【问题描述】:

我正在使用 PowerMock/EasyMock 测试一个静态方法,其中一个参数是一个 StringBuffer,该字符串缓冲区由该模拟类中的方法附加。

这是一个用于演示的简化类。

import java.util.Date;

public class ContentChanger
{
    public static int change(StringBuffer sb)
    {
        sb.append( new Date() );
        return 0;
    }
}

这是单元测试...

import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ContentChanger.class)
public class ContentChangerTest
{
    @Test
    public void test001()
    {
    // Declare an empty StringBuffer
    StringBuffer var = new StringBuffer();

    // Enable static mocking for the ContentChanger class
    PowerMock.mockStatic( ContentChanger.class );

    // Catch the call and send to test method
    EasyMock.expect(ContentChanger.change( var )).andDelegateTo( test(var) );

    // Replay all mock classes/methods
    PowerMock.replayAll();

    // Call the method to be mocked
    System.out.println( ContentChanger.change( var ) + " = " + var );
    }


    private int test( StringBuffer sb )
    {
        sb.append( "Mocked" );
        return 1;
    }
}

我期望发生的是调用测试方法并输出 StringBuffer..

1 = 嘲笑

但是发生的情况是 StringBuffer 变量在调用模拟方法之前更新。

即我得到以下...

java.lang.AssertionError: 
  Unexpected method call ContentChanger.change(Mocked):
    ContentChanger.change(Mocked): expected: 1, actual: 2

有没有办法调用另一个类/方法,以在调用时更改参数的内容而不是预重放。

【问题讨论】:

    标签: java junit powermock easymock


    【解决方案1】:

    问题是你打电话给test(var)andDelegateTo 期望 Object 与 mock 具有相同的类/接口。见http://easymock.org/user-guide.html#verification-creating

    由于您使用的是静态方法,因此这是不可能的。所以最好是改用 IAnswer。这是工作代码:

            EasyMock.expect(ContentChanger.change( var )).andAnswer(new IAnswer<Integer>() {
            @Override
            public Integer answer() throws Throwable {
                StringBuffer sb = (StringBuffer) EasyMock.getCurrentArguments()[0];
                sb.append( "Mocked" );
                return 1;
            }
        })
    

    【讨论】:

    • 作为评论,我认为 EasyMock 应该验证传递给 andDelegateTo 的类型。此外,actual: 2 似乎是一个错误。
    • 我会评论我之前的评论。这是半个错误。委托调用最终调用静态方法。这就是为什么我们有 2。这很难解释,但假设是 PowerMock 无法验证 EasyMock 中发生的事情,而 EasyMock 不知道可以模拟静态方法
    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多