为什么我必须扩展PowerMockTestCase?

时间:2015-02-20 04:31:13

标签: unit-testing mocking testng powermock easymock

当我不从PowerMockTestCase扩展时,下面的测试会抛出java.lang.IllegalStateException: no last call on a mock available

一旦从PowerMockTestCase扩展,错误就会消失。为什么会发生这种情况?

import static org.junit.Assert.assertEquals;

import org.easymock.EasyMock;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;

@PrepareForTest({ IdGenerator.class, ServiceRegistartor.class })
public class SnippetTest extends PowerMockTestCase{

    @org.testng.annotations.Test
    public void testRegisterService() throws Exception {
        long expectedId = 42;

        // We create a new instance of test class under test as usually.
        ServiceRegistartor tested = new ServiceRegistartor();

        // This is the way to tell PowerMock to mock all static methods of a
        // given class
        PowerMock.mockStatic(IdGenerator.class);

        /*
         * The static method call to IdGenerator.generateNewId() expectation.
         * This is why we need PowerMock.
         */
        EasyMock.expect(IdGenerator.generateNewId()).andReturn(expectedId).once();

        // Note how we replay the class, not the instance!
        PowerMock.replay(IdGenerator.class);

        long actualId = tested.registerService(new Object());

        // Note how we verify the class, not the instance!
        PowerMock.verify(IdGenerator.class);

        // Assert that the ID is correct
        assertEquals(expectedId, actualId);
    }

}

2 个答案:

答案 0 :(得分:3)

使用PowerMock进行静态模拟时,会发生一个类级别的工具来进行模拟工作。 PowerMockTestCase类有一个代码(方法beforePowerMockTestClass()),可以将常规类加载器切换到powermock类加载器,它可以编排模拟注入。因此,您需要扩展此类以使静态模拟工作。

答案 1 :(得分:0)

您需要配置PowerMock类加载器,以便可以拦截静态类(使用@PrepareForTest批注定义)。

您不必从 PowerMockTestCase 扩展。在大多数情况下,您也可以使用 PowerMockObjectFactory 配置TestNG:

@PrepareForTest({ IdGenerator.class, ServiceRegistartor.class })
public class SnippetTest {

   @ObjectFactory
   public IObjectFactory objectFactory() {
      return new PowerMockObjectFactory();
   }

   @org.testng.annotations.Test
   public void testRegisterService() throws Exception {
      ...
   }
}