如何编写init()的junit?

时间:2017-03-17 07:00:40

标签: java servlets junit

您好,我是junit的初学者,我偶然发现了我在servlet中定义的init()方法的junit。

这是我的servlet。

  public class EmailSendingServlet extends HttpServlet{

        private static final long serialVersionUID = -7796409155466523414L;

        /**
         * Creates an Email Model Object
         */
        Email emailMessage = new Email();

        /**
         * Overrides the init constructor of servlet
         * 
         */
        public void init() {
            ServletContext context = getServletContext();
            emailMessage.setHostName(context.getInitParameter("host"));
            emailMessage.setPortName(context.getInitParameter("port")); 
        }
        /**
         * Overrides the Service method of Generic Servlet 
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


            emailMessage.setFrom(request.getParameter("from"));
            emailMessage.setRecipient(request.getParameterValues("recipients"));
            emailMessage.setSubject(request.getParameter("subject"));
            emailMessage.setBody(request.getParameter("body"));
            emailMessage.setFile(request.getParameterValues("file"));

            String resultMessage = "";

            try {
                EmailUtility.sendEmail(emailMessage);
                resultMessage = "The Email was sent successfully";
                request.setAttribute("message", resultMessage);
                response.setContentType("text/html");
                RequestDispatcher view = request.getRequestDispatcher("/Result.jsp");
                view.forward(request, response);

            } catch (Exception e) {

                e.printStackTrace();
            }
        }

以下给出的是我的servlet类的测试用例:

@RunWith(PowerMockRunner.class)

    public class EmailSendingServletTest extends Mockito
    {

        @Test
        public void TestEmailSendingServlet() {

            HttpServletRequest request = mock(HttpServletRequest.class);
            HttpServletResponse response = mock(HttpServletResponse.class);
            RequestDispatcher requestDispatcher = mock(RequestDispatcher.class);

            when(request.getParameter("from")).thenReturn("robi@robi.com");
            String[] recipients = new String [3];
            recipients[0] = "abc@abc.com";
            recipients[1] = "xyz@xyz.com";
            recipients[2] = "qwe@qwe.com";
            when(request.getParameterValues("recipients")).thenReturn(recipients);
            when(request.getParameter("subject")).thenReturn("Test Mail");
            when(request.getParameter("body")).thenReturn("This is Body");
            String[] files = new String[1];
            files[0] = "C:\\Users\\asara3\\Documents\\Architecture.jpg";
            when(request.getParameterValues("file")).thenReturn(files);
            when(request.getRequestDispatcher("/Result.jsp")).thenReturn(requestDispatcher);

            try {
                new EmailSendingServlet().doPost(request, response);
            } catch (ServletException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }


        }

我有点困惑在我的测试用例中存根context.getInitParameter(" host")?有帮助吗?

1 个答案:

答案 0 :(得分:2)

您可以使用Mockito的spy()方法来模拟getServletContext()方法的行为。

例如,在setup()方法或单元测试类的构造函数中添加它:

public class EmailSendingServletTest {
  ...
  private EmailSendingServlet emailSendingServlet;
  private EmailSendingServlet emailSendingServletSpy;
  ...

  public EmailSendingServletTest(){
    emailSendingServlet =  new EmailSendingServlet();
    emailSendingServletSpy = Mockito.spy(emailSendingServlet);
  }
}

然后你可以像这样模拟getServletContext()方法:

Mockito.doReturn(yourMockedServletContext).when(emailSendingServletSpy.getServletContext());

通常我会避免间谍(嘲笑被测对象),但是在第三方依赖作为servlet的情况下,这是一个可以接受的情况,因为重构是不能的,否则它会迫使我们不写标准的改变方式使用第三方依赖项。这通常也是不受欢迎的。