PowerMockito:如何模拟Singleton的私有成员

时间:2013-12-15 02:18:45

标签: 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();
     ....
  }
}

我尝试了以下内容,但无济于事:

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

问题是HandlerMgr.getHandler()仍然被调用,我想绕过它并模拟它。

2 个答案:

答案 0 :(得分:0)

根据我的评论

您的Controller调用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,真正的方法仍然被调用。

答案 1 :(得分:0)

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