简体   繁体   English

当... thenResult始终返回null时,进行模拟

[英]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: 我有这个其余的Java函数:

@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");? 为什么在SessionFactory sessionFactory =(SessionFactory)context.getAttribute(“ SessionFactory”);中总是使用空指针崩溃?

Other mockito issue 其他模仿问题

Fixed. 固定。

I have changed the java app adding the method 我已经更改了添加方法的Java应用程序

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! 感谢大家!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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