簡體   English   中英

Mockito:如何單元測試void方法Java Mockito?

[英]Mockito: How do unit test void method 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");} 

謝謝 :)。

您可以使用mock對象或spy對象來驗證預期的行為。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM