Mockito:如何进行单元测试void方法java mockito?

问题描述 投票:1回答:1

我有以下代码我想进行单元测试:

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);
      }
  }

我需要验证方法validarEntero或方法generateErrorProcessingFile是否执行,因为两个方法都不返回任何内容。

这是我做的:

@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");} 

谢谢 :)。

java mockito junit5
1个回答
0
投票

您可以使用mockspy对象来验证预期的行为。

@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");
}
© www.soinside.com 2019 - 2024. All rights reserved.