繁体   English   中英

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

[英]Mockito when…thenResult always returns null Part 2

解决了第一个模拟问题之后,我找到了第二个(非常类似于第一个,但是我不知道如何解决)

我有这个其余的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");

和这个测试:

@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");    
}

为什么在SessionFactory sessionFactory =(SessionFactory)context.getAttribute(“ SessionFactory”);中总是使用空指针崩溃?

其他模仿问题

固定。

我已经更改了添加方法的Java应用程序

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

我用以下方法更改了测试:

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

    }

有了它,就可以了。 感谢大家!

暂无
暂无

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

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