Aja*_*jay 5 testng unit-testing easymock mocking powermock
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在使用 PowerMock 进行静态模拟时,会发生类级别的检测来使您的模拟工作。PowerMockTestCase 类有一个代码(beforePowerMockTestClass() 方法),用于将常规类加载器切换到 powermock 类加载器,后者负责编排模拟注入。因此,您需要扩展此类才能使静态模拟正常工作。
| 归档时间: |
|
| 查看次数: |
4129 次 |
| 最近记录: |