【问题标题】:Why do I have to extend PowerMockTestCase?为什么我必须扩展 PowerMockTestCase?
【发布时间】:2015-02-20 04:31:12
【问题描述】:

当我不从 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);
    }

}

【问题讨论】:

  • 它在哪一行给出了这个异常?你能把异常跟踪,它可能会有所帮助
  • 对不起@vihar 我没有这个设置了。但据我所知,它是从 PowerMock.replay(IdGenerator.class); 线抛出的;
  • 好的,要么关闭这个问题,要么自己回答

标签: unit-testing mocking testng powermock easymock


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您需要配置 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 {
          ...
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2020-08-09
      • 1970-01-01
      • 2010-09-29
      相关资源
      最近更新 更多