简体   繁体   中英

Mockito when…thenResult always returns null Part 2

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

Other mockito issue

Fixed.

I have changed the java app adding the method

protected void setContext(ServletContext context)
    {
        this.context= context;
    }

and i have changed the test with:

 @Override
    @BeforeClass
    public void setUp() throws Exception {
        context =  mock (ServletContext.class, RETURNS_DEEP_STUBS);
        employeeOps = new EmployeeOps();
        employeeOps.setContext(context);
    }

    @Test
    public void testDeleteServlet() throws Exception {

        SessionFactory factory = contextInitialized();
        when(context.getAttribute("SessionFactory")).thenReturn(factory);
        employeeOps.deleteEmployee("41");

    }

With this it works fine. Thanks everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM