-1

Is there any way to write a mockito test case for the particular case.

public void saveStaffInfo(HttpServletResponse response, RegBean regdata, Staffinfo staffType, boolean status) 
throws IOException {

    if (status) 
    {
        boolean status1 = staffType.insertlogin(regdata);
        if(status1) {
            response.sendRedirect("registration.jsp?status=success");
        }
        else {
            response.sendRedirect("registration.jsp?status=login_table_error");   
        }
    } else {
        response.sendRedirect("registration.jsp?status=failed"); 
    } 
}

I did mock the HttpServeletResponse, RegBean,Staffinfo. However, as it is of void type so I cannot use doReturn().when(mockedMethod).(someMethod). So how do I test these lines? I also need code coverage. I am very new to this. The test case

@Test
public void testSaveStaffInfo() throws IOException, ServletException{
    boolean status =true;
    // System.out.println(iStaffInfo.insertlogin(regdata));
    Mockito.when(iStaffInfo.insertlogin(regdata)).thenReturn(Boolean.TRUE );
    reg.saveStaffInfo(response, regdata, iStaffInfo,status);     
}
Bentaye
  • 9,403
  • 5
  • 32
  • 45
Spell Blade
  • 109
  • 2
  • 6
  • 1
    Without the test it is hard to tell. You shouldn't mock the input, but rather mock the `staffType`. For the response use the `MockHttpServletResponse` to test and verify afterwards. Or just write a proper Spring MVC test using MockMVC (which is more of an integration test). – M. Deinum Mar 02 '20 at 10:36
  • Please add the failing tests and the error you are getting. Also say what line in the test is causing the NullPointerException – Bentaye Mar 02 '20 at 10:37
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – M. Prokhorov Mar 02 '20 at 10:41
  • 1
    Seems to me that either `staffType` or `response` is null. What line is throwing the NullPointerException? – Bentaye Mar 02 '20 at 11:08
  • What you want to do in this case is to `verify` that the correct method on your response `mock` has been called. You can combine this with the use of an `ArgumentCaptor` to check that the correct argument has been passed. – second Mar 02 '20 at 20:38

1 Answers1

0

You need to think what it is you want to test here. What is the "output"? The "output" here is that the method is doing something to your HttpServletResponse, it is calling sendRedirect.

You can verify that certain methods are being called on your mocked (or real) objects with Mockito.verify

kutschkem
  • 7,826
  • 3
  • 21
  • 56