Quantcast
Channel: Active questions tagged servlets - Stack Overflow
Viewing all articles
Browse latest Browse all 714

Unit Testing Unit test Servlet with Mockito: Mocked Behavior Not Executing

$
0
0

I'm encountering an issue while writing a unit test for my servlet using Mockito. I'm attempting to mock the behavior of a Business Object (BO) object using doAnswer to set a test value to a Value Object (VO) object. However, it seems that the original BO object's behavior is still executing instead of the mocked behavior.Here's a simplified version of my servlet's doGet method:

@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {MyVO myVO = new MyVO();try (Connection connection = DBConnectionPooler.getDatabaseConnection("DBNAME")) {    RequestDispatcher view;    new MyBO().getAllItems(connection, myVO);    request.setAttribute("myList", myVO.getMyList());    view = request.getRequestDispatcher("/someJSP.jsp");    view.forward(request, response);} catch (Exception e) {    logger.error(e);}

}

And here's the relevant part of my test method using Mockito:

@Testvoid testGetRequest() {try {    RequestDispatcher rd = mock(RequestDispatcher.class);    HttpServletRequest request = mock(HttpServletRequest.class);    HttpServletResponse response = mock(HttpServletResponse.class);    MyBO myBO = mock(MyBO.class);    MyVO myVO = new MyVO();    List<TestObject> testList = new ArrayList<>();    testList.add(new TestObject());    testList.add(new TestObject());    doAnswer(invocation -> {        MyVO arg = invocation.getArgument(1);        arg.setMyList(testList);        return null;    }).when(myBO).getAllItems(any(Connection.class), eq(myVO));when(request.getRequestDispatcher("/someJSP.jsp")).thenReturn(rd);    myServlet.doGet(request, response);    verify(request).setAttribute("myList", testList);    verify(rd).forward(request, response);} catch (IOException | ServletException e) {    e.printStackTrace();    fail();}

}

The issue arises when verifying request.setAttribute("myList", testList). The expected value is testList, but the actual value seems to be coming from the actual database instead of the mocked behavior.I'm using Mockito version 5.11.0 and JUnit version 5.10.2.Any insights or suggestions on what might be causing this discrepancy would be greatly appreciated. Thank you!


Viewing all articles
Browse latest Browse all 714

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>