Java PowerMockito:如何模拟单身人士的私人成员
我尝试测试以下遗留单例类:Java PowerMockito:如何模拟单身人士的私人成员,java,unit-testing,mockito,powermock,Java,Unit Testing,Mockito,Powermock,我尝试测试以下遗留单例类: public class Controller { private handler = HandlerMgr.getHandler(); public static final instance = new Controller(); private Controller() { } public int process() { List<Request> reqs = handler.getHandler();
public class Controller {
private handler = HandlerMgr.getHandler();
public static final instance = new Controller();
private Controller() {
}
public int process() {
List<Request> reqs = handler.getHandler();
....
}
}
问题是HandlerMgr.getHandler()仍然会被调用,我想绕过它并模拟它。根据我的评论
您的控制器调用getHandler,但设置GetRequest的期望值?这是 可能是为什么真正的方法会被调用 然后参考文档,您似乎缺少对mockStatic生成的存根的期望 根据PowerMock文档。。。请看下面
@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
mockStatic(IdGenerator.class);
/*
* The static method call to IdGenerator.generateNewId() expectation.
* This is why we need PowerMock.
*/
expect(IdGenerator.generateNewId()).andReturn(expectedId);
// Note how we replay the class, not the instance!
replay(IdGenerator.class);
long actualId = tested.registerService(new Object());
// Note how we verify the class, not the instance!
verify(IdGenerator.class);
// Assert that the ID is correct
assertEquals(expectedId, actualId);
}
由于您的期望/设置缺少grtHandler,实际的方法仍然会被调用。将@PrepareForTest({HandlerMgr.class})添加到测试类中。您问题是HandlerMgr.getHandler()仍然会被调用,我想绕过它并模拟它。您的控制器调用getHandler,但对GetRequest设置期望?这可能就是调用实际方法的原因?您需要在(HandlerMgr.getHandler())时执行一些以
开头的存根操作。
@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
mockStatic(IdGenerator.class);
/*
* The static method call to IdGenerator.generateNewId() expectation.
* This is why we need PowerMock.
*/
expect(IdGenerator.generateNewId()).andReturn(expectedId);
// Note how we replay the class, not the instance!
replay(IdGenerator.class);
long actualId = tested.registerService(new Object());
// Note how we verify the class, not the instance!
verify(IdGenerator.class);
// Assert that the ID is correct
assertEquals(expectedId, actualId);
}