gpt4 book ai didi

unit-testing - 为什么我必须扩展 PowerMockTestCase?

转载 作者:行者123 更新时间:2023-12-04 05:26:37 26 4
gpt4 key购买 nike

下面的测试抛出 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com