-2

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

Srividya
  • 119
  • 1
  • 1
  • 9
  • 1
    `I am trying to mock the prepare() in the test class`. ? Show what you tried in the test class. – Nkosi Sep 19 '19 at 11:33
  • Are you following TDD or BDD approach?, if you're following TDD approach then don't go with solution suggested. And also don't use spy since code smells when you use spy. – Praveen Kumar Mekala Sep 23 '19 at 12:23

1 Answers1

1

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()
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63