1

我正在尝试使用 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)
4

1 回答 1

1

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

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

于 2013-08-11T01:20:57.407 回答