使用EasyMock将Powermock与TestNG配合使用。抛出异常

时间:2013-08-11 01:17:10

标签: java unit-testing testng easymock powermock

我正在尝试使用Powermock编写一个TestNg测试来模拟静态函数调用。 我的测试代码是:

import static org.easymock.EasyMock.expect;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.easymock.PowerMock.verify;

import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.Assert;
import org.testng.annotations.Test;


@PrepareForTest(TestStringProvider.class)
public class TryPowerMock {

    public void test() {
        String string = TestStringProvider.getString();
        Assert.assertEquals(string, "testString");
    }

    @Test
    public void tryPowerMock() {
        mockStatic(TestStringProvider.class);        
        expect(TestStringProvider.getString()).andReturn("testString");
        replay(TestStringProvider.class);
        test();
        verify(TestStringProvider.class);
    }

}

具有静态功能的类:

public class TestStringProvider {
    public static String getString(){
        return "WHY AM I CALLED, I AM SUPPOSED TO BE MOCKED";
    }

}

运行此测试会给我以下异常,

FAILED: tryPowerMock
java.lang.IllegalStateException: no last call on a mock available
    at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:520)
    at org.easymock.EasyMock.expect(EasyMock.java:498)
    at com.archit.learn.powermock.TryPowerMock.tryPowerMock(TryPowerMock.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

1 个答案:

答案 0 :(得分:1)

更多探索并自己找到解决方案。

我不得不从PowerMockTestCase类扩展我的单元测试