随笔-61  评论-159  文章-0  trackbacks-0
easymock的测试:
         1、  首先导入easymock.jar包。
         2、 LoginServlet.java  servlet类

 1package com.test.mock;
 2
 3import java.io.IOException;
 4
 5import javax.servlet.RequestDispatcher;
 6import javax.servlet.ServletContext;
 7import javax.servlet.ServletException;
 8import javax.servlet.http.HttpServlet;
 9import javax.servlet.http.HttpServletRequest;
10import javax.servlet.http.HttpServletResponse;
11
12public class LoginServlet extends HttpServlet {
13    /**
14     * 
15     */

16    private static final long serialVersionUID = 7020197334019200211L;
17
18    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19        String username = request.getParameter("username");
20        String password = request.getParameter("password");
21        // check username & password:
22        if("admin".equals(username) && "123456".equals(password)) {
23            ServletContext context = getServletContext();
24            RequestDispatcher dispatcher = context.getNamedDispatcher("dispatcher");
25            dispatcher.forward(request, response);
26        }

27        else {
28            throw new RuntimeException("Login failed.");
29        }

30    }

31
32
33}

34

            3、LoginServletTest.java

 1package com.test.mock;
 2
 3import javax.servlet.http.*;
 4import org.easymock.*;
 5import junit.framework.TestCase;
 6public class LoginServletTest extends TestCase {    
 7    public void testLoginFailed() throws Exception {        
 8        MockControl mc = MockControl.createControl(HttpServletRequest.class);        
 9        HttpServletRequest request = (HttpServletRequest)mc.getMock();        
10    request.getParameter("username");        
11        mc.setReturnValue("admin"1);        
12        request.getParameter("password");        
13        mc.setReturnValue("1234"1);        
14  
15        mc.replay();                
16        LoginServlet servlet = new LoginServlet();        
17        try {            
18            servlet.doPost(request, null);            
19            fail("Not caught exception!");        }
        
20        catch(RuntimeException re) {            
21            assertEquals("Login failed.", re.getMessage());        
22            }
               
23        mc.verify();    
24        }
    
25}


测试结果:



-------------------------------------------------------------------------------------------------
PS:本博客文章,如果没有注明是有“转”字样,属于本人原创。如果需要转载,务必注明作者文章的详细出处地址,否则不允许转载,多谢合作!
posted on 2007-09-16 17:33 apple0668 阅读(411) 评论(0)  编辑  收藏 所属分类: junit

只有注册用户登录后才能发表评论。


网站导航: