Maven+Jetty+HttpClient测试Servlet

1、开发自己的Servlet

2、在pom.xml文件中添加必要的支持

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
            <scope>provided</scope>
 </dependency>
<dependency>
           <groupId>org.mortbay.jetty</groupId>
            <artifactId>jetty</artifactId>
            <version>6.1.25</version>
           <scope>test</scope>
 </dependency>
<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.1.2</version>
</dependency>
<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
 </dependency>

注意:最好不要使用最新版本的servlet-api和jetty。在最新的jetty中增强了Cookie的操作,会调用setHttpOnly方法,而这时servlet3.0中的规范,

从Maven中下载3.0的servlet-api也不支持该方法,执行将出错。


3、测试用例的编写

   
    // 创建Servlet的运行环境
    public static Server server;
    
    @Override
    protected void setUp() throws Exception {
        // TODO Auto-generated method stub
        super.setUp();
        
        server = new Server(99);
        Context root = new Context(server,"/",Context.SESSIONS);
        root.addServlet(new ServletHolder(new servletName()), "/servletpath");//此处写servlet-mapping的类名和路径
        server.start();
    }

    @Test
    public void testLogin1() {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost method = new HttpPost("http://localhost:99/servletpath");
        
        ByteArrayEntity reqEntity = new ByteArrayEntity ("123".getBytes());
        method.setEntity(reqEntity);
        
        HttpResponse response;
        try {
            response = httpclient.execute(method);

            HttpEntity resEntity = response.getEntity();
            
            assertNotNull(resEntity);            
            assertEquals(response.getStatusLine().getStatusCode(), 200);
        } catch (ClientProtocolException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            Assert.fail();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            Assert.fail();
        }
    }

    @Override
    protected void tearDown() throws Exception {
        // TODO Auto-generated method stub
        super.tearDown();
        server.stop();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值