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



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

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

谢谢:)。

您可以使用

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

相关内容

  • 没有找到相关文章

最新更新