如何通过 mockito 初始化 Servlet Config [英] how to Initialize Servlet Config through mockito

查看:97
本文介绍了如何通过 mockito 初始化 Servlet Config的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 servlet 编写测试用例.在测试中,我无法初始化 Servlet 配置变量.我也提供我的代码和测试

I am writing test case for servlets. In Test I am not able to intiallize Servlet Config variable. I am providing my code and test also

代码是:

   public void service (HttpServletRequest request,
                        HttpServletResponse response)
throws ServletException, IOException
{


    ServletConfig config = getServletConfig();

    msSmtpServer    = getServletConfig().getInitParameter("smptserver");
    msSmtpPort      = getServletConfig().getInitParameter("smtpport");
    msUserName      = getServletConfig().getInitParameter("username");
    msPassword      = getServletConfig().getInitParameter("password");

    String buf = getRequestBuffer(request).toString();

和测试是:

public class AddUserServletTest {
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Mock
HttpSession session;
@Mock
RequestDispatcher rd;
@Mock
ServletOutputStream  servletOut;
@Mock
ServletConfig sg;
public final static String Seperator = new Character((char)1).toString();
public final static String ContentDelimeter = new Character((char)2).toString();

@BeforeClass
public void setUp() throws Exception 
{
    MockitoAnnotations.initMocks(this);
}

@Test
public void test() throws Exception {
    DataSet ds=new DataSet();

    String buffer=ds.getUserId()+Seperator+ds.getTableID()+Seperator+ds.getMemberID()+Seperator+ds.getNHID();
    ByteArrayOutputStream bos = new ByteArrayOutputStream ();
    ZipOutputStream out = new ZipOutputStream(bos);
    out.putNextEntry(new ZipEntry("request.txt"));
    out.write(buffer.getBytes("UTF-8"));
    out.closeEntry();
    out.close ();
    bos.close();

    String b64String = Base64.encodeBase64String(bos.toByteArray());
    Reader inputString = new StringReader(b64String);
    BufferedReader reqbuffer = new BufferedReader(inputString);

    when(request.getReader()).thenReturn(reqbuffer);
    when(sg.getInitParameter("smptserver")).thenReturn("abc.xyz.com");
    when(sg.getInitParameter("smtpport")).thenReturn("80");
    when(sg.getInitParameter("username")).thenReturn("password@xyz.com");
    when(sg.getInitParameter("password")).thenReturn("abcd");
    when(response.getOutputStream()).thenReturn(servletOut);

    new AddUsers().service(request, response);

    ArgumentCaptor<String> bufferCaptor = ArgumentCaptor.forClass(String.class);
    verify(servletOut).print(bufferCaptor.capture());
    String responseBody = bufferCaptor.getValue();       

    ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(Base64.decodeBase64(responseBody.toString().getBytes())));
    zipIn.getNextEntry();
    StringBuffer sb = new StringBuffer();
    ByteArrayOutputStream out1 = new ByteArrayOutputStream();
    IOUtils.copy(zipIn, out1);
    sb = new StringBuffer();
    sb.append(out1.toString("UTF-8"));
    System.out.println("--------------- :"+sb.toString());
    String[] res=sb.toString().split(Seperator);        
    AssertJUnit.assertEquals("Success",res[0]);
}
}

我尝试初始化,但在 servlet 中,值为 null 未获取值.

i tried to initialize but in servlet that values are null not getting values.

如何在测试中使用 mockito 初始化 ServletConfig 变量?

How to initialize ServletConfig variable in test using mockito?

推荐答案

当前代码:

new AddUsers().service(request, response);

创建 servlet 的一个新实例并尝试立即使用它,因此该实例不知道 sg.

creates a new instance of the servlet and attempts to use it immediately so the instance has no awareness of sg.

试试这个,它允许在使用之前注入模拟:

Try this which allows the mock to be injected before using it:

AddUsers servlet = new AddUsers();
 servlet.init(sg);  // use the servlet life-cycle method to inject the mock
servlet.service(request, response);

这篇关于如何通过 mockito 初始化 Servlet Config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆