作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面的测试抛出 java.lang.IllegalStateException: no last call on a mock available
当我不从 PowerMockTestCase 扩展时。
一旦我从 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);
}
}
最佳答案
在使用 PowerMock 进行静态模拟时,会发生一个类级别的工具来使您的模拟工作。 PowerMockTestCase 类有一个代码(方法 beforePowerMockTestClass())将您的常规类加载器切换到协调模拟注入(inject)的 powermock 类加载器。因此,您需要扩展此类以使静态模拟起作用。
关于unit-testing - 为什么我必须扩展 PowerMockTestCase?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28621653/
下面的测试抛出 java.lang.IllegalStateException: no last call on a mock available当我不从 PowerMockTestCase 扩展时。
我是一名优秀的程序员,十分优秀!