使用Mock对Servlet进行Junit单元测试

使用jar包:mockito-all-1.8.5.jar 和Junit4

import static org.mockito.BDDMockito.given;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import au.com.aiaa.claims.util.BeanMapperUtil;

import junit.framework.Assert;

public class UserServletTest {
    @Mock
    private HttpServletRequest request;
    @Mock
    private HttpServletResponse response;
    @Mock
    private ServletConfig servletConfig;
    @Mock
    private ServletContext servletContext;
    private UserServlet instance;

    @Before
    public void init() throws IOException {
        MockitoAnnotations.initMocks(this);
        instance = new UserServlet ();
   }

    @Test
    public void testVersionServlet() throws Exception {
        instance.init(servletConfig);
        given(servletConfig.getServletContext()).willReturn(servletContext);
        PrintWriter pw = new PrintWriter(System.out, true);
        given(response.getWriter()).willReturn(pw);
        instance.doGet(request, response);
        pw.flush();
        verify(response);
    }

    private void verify(HttpServletResponse response) {
        Assert.assertNotNull(response);
    }
}

 

你可能感兴趣的:(servlet)