简体   繁体   中英

Mockito: How do unit test void method java mockito?

I have following code I want to unit test:

public class TransformarExcel
{

public TransformarExcel() {
    //Constructor
}
  public void validarEntero(HttpServletRequest request, HttpServletResponse response, Integer rowCount, String column, String value)
  {
    if (value.equals("0")) {
      generateErrorProcessingFile(request, response, ALERTDANGER, MSGCOLUMNA + column + MSGREGISTRO + rowCount + " no puede ser vacío.");
    }
  }

  public void generateErrorProcessingFile(HttpServletRequest request, HttpServletResponse response, String typeError, String messageError)
  {
      request.setAttribute("typeMessage", typeError);
      request.setAttribute("message", messageError);
      try {
          request.getRequestDispatcher("index.jsp").forward(request, response);
      } catch (ServletException|IOException ex) {
          Logger.getLogger(ServletTransformarExcelDesembolso.class.getName()).log(Level.SEVERE, null, ex);
      }
  }

I need to verify that method validarEntero or the method generateErrorProcessingFile are execute, Since both methods do not return anything.

This is I do:

@Test
final void testValidarEntero() throws IOException {

        ServletTransformarExcelDesembolso manager = Mockito.mock(ServletTransformarExcelDesembolso.class);
        ServletTransformarExcelDesembolso dato = new ServletTransformarExcelDesembolso(); 
        dato.validarEntero(null, null, null, null, "0");
        verify(manager, Mockito.timeout(1)).validarEntero(null, null, null, null, "0");} 

Thank you :).

You can use mock or spy objects to verify expected behaviour.

@Test
final void testValidarEntero() throws IOException {

    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    Mockito.when(mockRequest.getRequestDispatcher(anyString())).thenReturn(Mockito.mock(RequestDispatcher.class));

    ServletTransformarExcelDesembolso dato = new ServletTransformarExcelDesembolso(); 
    dato.validarEntero(mockRequest, null, null, null, "0");

    verify(mockRequest, Mockito.times(1)).getRequestDispatcher("index.jsp");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM