Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 为什么我必须扩展PowerMockTestCase?_Unit Testing_Mocking_Testng_Powermock_Easymock - Fatal编程技术网

Unit testing 为什么我必须扩展PowerMockTestCase?

Unit testing 为什么我必须扩展PowerMockTestCase?,unit-testing,mocking,testng,powermock,easymock,Unit Testing,Mocking,Testng,Powermock,Easymock,下面的测试抛出java.lang.IllegalStateException:当我没有从PowerMockTestCase扩展时,没有最后一次调用可用的模拟 从PowerMockTestCase扩展后,错误立即消失。这到底是为什么 导入静态org.junit.Assert.assertEquals; 导入org.easymock.easymock; 导入org.powermock.api.easymock.powermock; 导入org.powermock.core.classloader.a

下面的测试抛出
java.lang.IllegalStateException:当我没有从PowerMockTestCase扩展时,没有最后一次调用可用的模拟

从PowerMockTestCase扩展后,错误立即消失。这到底是为什么

导入静态org.junit.Assert.assertEquals;
导入org.easymock.easymock;
导入org.powermock.api.easymock.powermock;
导入org.powermock.core.classloader.annotations.PrepareForTest;
导入org.powermock.modules.testng.PowerMockTestCase;
@PrepareForTest({IdGenerator.class,ServiceRegistrator.class})
公共类SnippetTest扩展了PowerMockTestCase{
@org.testng.annotations.Test
public void testRegisterService()引发异常{
长期预期d=42;
//我们通常会创建一个测试类的新实例。
ServiceRegistrator tested=新ServiceRegistrator();
//这是告诉PowerMock模拟一个对象的所有静态方法的方法
//给定类
mockStatic(IdGenerator.class);
/*
*对IdGenerator.generateNewId()的静态方法调用。
*这就是我们需要PowerMock的原因。
*/
expect(IdGenerator.generateNewId()).andReturn(expectedId.once();
//注意我们如何重播类,而不是实例!
replay(IdGenerator.class);
long-implementId=tested.registerService(新对象());
//注意我们如何验证类,而不是实例!
验证(IdGenerator.class);
//断言ID是正确的
资产质量(预期、实现);
}
}

在使用PowerMock进行静态模拟时,会出现一个类级指令插入,以使模拟工作正常。PowerMockTestCase类有一个代码(方法beforePowerMockTestClass()),用于将常规类装入器切换到编排模拟注入的powermock类装入器。因此,您需要扩展该类以使静态模拟工作。

您需要配置PowerMock类装入器,以便可以拦截静态类(使用
@PrepareForTest
注释定义)

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


它在哪一行给出这个异常?你能把异常跟踪放进去吗,它可能会有帮助对不起@vihar我已经没有这个设置了。但据我记忆所及,它是从PowerMock.replay(IdGenerator.class)行抛出的;好的,要么关闭这个问题,要么自己回答
@PrepareForTest({ IdGenerator.class, ServiceRegistartor.class })
public class SnippetTest {

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

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