PowerMockito:如何嘲笑单身汉的私人成员



我正在尝试测试以下遗留的单例类:

public class Controller {
   private handler = HandlerMgr.getHandler();
   public static final instance = new Controller();
   private Controller() {
   }
  public int process() {
     List<Request> reqs = handler.getHandler();
     ....
  }
}

我尝试了以下方法,但没有成功:

  @Test
  public void test() {
    mockStatic(HandlerMgr.class);
    when(Handler.getHandler()).theReturn(expectedRequests);
    int actual = Controller.instance.process();
    // ... assertions ...
  }

问题是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);
}

https://code.google.com/p/powermock/wiki/MockStatic

由于您的期望/设置缺少grtHandler,因此仍会调用真正的方法。

将@PrepareForTest({HandlerMgr.class})添加到测试类中

相关内容

  • 没有找到相关文章