【发布时间】: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