gpt4 book ai didi

java - PowerMock - 如何调用操作模拟方法的参数

转载 作者:行者123 更新时间:2023-12-01 11:21:56 24 4
gpt4 key购买 nike

我正在使用 PowerMock/EasyMock 来测试静态方法,其中参数之一是 StringBuffer,该 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 = MOCKED

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

即我得到以下信息...

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

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

最佳答案

问题是您正在调用test(var)andDelegateTo 期望一个与模拟具有相同类/接口(interface)的对象。请参阅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;
}
})

关于java - PowerMock - 如何调用操作模拟方法的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31121814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com