Search code examples
sessionjunitmockitopowermockito

how to mock methods in the superclass through Mockito?


I am very new to Mockito framework and got blocked in the following scenario. I have two classes A and B

Class A{
    public HttpServletRequest getHttpReq() {
          return httpReq;
    }
}
Class B extends A{
     public void prepare() throws Exception{
        HttpSession session = getHttpReq().getSession();
     }
}

I am trying to mock the prepare() in the test class. Tried different ways and none of them works. Could anyone please help me out in how to mock getHttpReq().getSession() in the test class. Thanks in advance


Solution

  • In your test instead of instantiating the B class directly, wrap it with Mockito spying feature:

    B b = Mocktio.spy(new B());
    

    Then you can use standard stubbing to achieve what you need:

    doReturn(new HttpServletRequest()).when(b).getHttpReq()