when thenReturn always returns null

7,979 views
Skip to first unread message

carlos hernando

unread,
Jan 5, 2016, 6:27:37 PM1/5/16
to mockito
Hi.

With the above code i always get an error in line of test (     when(request.getServletContext().getAttribute("SessionFactory")).thenReturn(factory);)
Any ideas?

JAVA CLASS
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
SessionFactory sessionFactory = (SessionFactory) request.getServletContext().getAttribute("SessionFactory");
int empId =0;
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
try{
   empId = Integer.parseInt(request.getParameter("empId"));
logger.info("Request Param empId="+empId);
}catch (Exception e)
{
e.printStackTrace();
//response.sendError(Constants.EMPTY_PARAMETER_EMPID);-->Tentador pero peligroso hacerlo asi
response.addHeader(Constants.ERROR_CODE, Constants.EMPTY_PARAMETER_EMPID);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

tx.rollback();
return;
}
try{
session.delete((Employee) session.get(Employee.class, empId));
tx.commit();
}catch (Exception e)
{
e.printStackTrace();
response.addHeader(Constants.ERROR_CODE, Constants.ERROR_DELETING_USER);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
tx.rollback();
}
PrintWriter out = response.getWriter();
out.flush();

}

TEST CLASS

 @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    


        factory = contextInitialized();
       when(request.getServletContext().getAttribute("SessionFactory")).thenReturn(factory); //Always error here
        when(request.getParameter("empId")).thenReturn("35");
        PrintWriter writer = new PrintWriter("somefile.txt");
        when(response.getWriter()).thenReturn(writer);
    
       new DeleteEmployee().doGet(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(FileUtils.readFileToString(new File("somefile.txt"), "UTF-8")
                   .contains("My Expected String"));
    }

Malte Finsterwalder

unread,
Jan 6, 2016, 3:07:31 AM1/6/16
to mockito
If I see it correctly: "request.getServletContext()" is a call on a mock and the method is not mocked via a when-call, so it returns null.
you would have to code something like:

when(request.getServletContext()).thenReturn(contextMock);
when(contextMock.getAttriubte("SessionFactory")).thenReturn(factory);

Greetings,
   Malte
> --
> You received this message because you are subscribed to the Google Groups "mockito" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to mockito+u...@googlegroups.com.
> To post to this group, send email to moc...@googlegroups.com.
> Visit this group at https://groups.google.com/group/mockito.
> To view this discussion on the web visit https://groups.google.com/d/msgid/mockito/e10d83e8-7a08-43ca-bbd0-1b582453162b%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

carlos hernando

unread,
Jan 6, 2016, 4:10:38 AM1/6/16
to mockito

Awesome Malte, the way you have told me it works perfectly!.

Searching in other forums i saw that making this other way it works too:

HttpServletRequest request = mock(HttpServletRequest.class, RETURNS_DEEP_STUBS);       
Message has been deleted

KARR, DAVID

unread,
Jan 6, 2016, 6:37:26 PM1/6/16
to moc...@googlegroups.com

It helps to run your unit tests in the debugger.  If you stepped onto that line that gets the NPE, you’ll see that “context” is null.  The problem is, you’re creating a mocked context in your test, but you don’t store it anywhere that your CUT (code under test) can use it.

 

From: moc...@googlegroups.com [mailto:moc...@googlegroups.com] On Behalf Of carlos hernando
Sent: Wednesday, January 06, 2016 2:40 PM
To: mockito <moc...@googlegroups.com>
Subject: [mockito] Re: when thenReturn always returns null

 

After resolve mi first mockito issue, i found my second one(very similar to my first one, but i don't know how to fix it)

I have this rest java function:

@GET
    @Path("/deleteEmployee")
    @Produces("application/json")
    public ReturnCode  deleteEmployee(@QueryParam("empId") String empIdToDelete)
{
        ReturnCode returnCode = new ReturnCode(Constants.NO_ERROR_CODE, Constants.NO_ERROR_TEXT);
        SessionFactory sessionFactory = (SessionFactory) context.getAttribute("SessionFactory");

and this test:

 @Test
    public void testDeleteServlet() throws Exception {
        ServletContext context =  mock (ServletContext.class, RETURNS_DEEP_STUBS);
        SessionFactory factory = contextInitialized();
 
        when(context.getAttribute("SessionFactory")).thenReturn(factory);
       new EmployeeOps().deleteEmployee("33");
 
    }

Why always crashes with null pointer in SessionFactory sessionFactory = (SessionFactory) context.getAttribute("SessionFactory");?

--
You received this message because you are subscribed to the Google Groups "mockito" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mockito+u...@googlegroups.com.
To post to this group, send email to moc...@googlegroups.com.
Visit this group at https://groups.google.com/group/mockito.

Reply all
Reply to author
Forward
0 new messages