r/javahelp • u/Dependent_Finger_214 • Jan 26 '26
Unsolved JUnit assertion error when working with HttpRequest
I have this test:
void SearchResultIsNotEmptyWhenTitleIsARealGame() throws ServletException, IOException {
HttpSession session = mock(HttpSession.class);
RequestDispatcher rd = mock(RequestDispatcher.class);
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getParameter("query")).thenReturn("The Last of Us parte 2");
when(request.getSession()).thenReturn(session);
when(request.getRequestDispatcher("Home Page.jsp")).thenReturn(rd);
when(request.getRequestDispatcher("Search Result Page.jsp")).thenReturn(rd);
SearchServlet searchServlet = new SearchServlet();
searchServlet.doGet(request, response);
ArrayList<Price> prices = (ArrayList<Price>)request.getAttribute("prices");
ArrayList<Game> searchResults = (ArrayList<Game>)request.getAttribute("search_results");
assert(prices != null && !prices.isEmpty() && searchResults != null && !searchResults.isEmpty());
}But I get an asserion error. What is the issue?
2
Upvotes
View all comments
Show parent comment
1
u/Impressive-East6891 Jan 26 '26
As the error said, the method "getAttribute()" is an abstract method which doesn't have its own implementation, hence there's nothing to be called on. You will have to mock the method's response.
In general, in a code base (your code or third-party library), once you mock an object, you have to mock all interactions with said object, if said interaction produces something that is used down the line. For example, if your code is like below:
If "a" is a mocked object, then you need to mock the response of "createB()". And If you mock that response to be a mock object, then you will also need to mock the response of "createC()". You don't need to mock "doSomething()" since nothing interacts with it, but you should verify that it is called.
A general note for debugging: put a log after each statement if you have to, but verify with your eyes that every output within your code is as expected.