【发布时间】: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