Spring3.1 mvc + junit4

1.所需要的jar

1).commons-dbcp-1.4

2).junit-4.12

3).spring-test-3.1.4.RELEASE

4).org.hamcrest.core

5).spring框架其他相关依赖的jar

注意:以上是在spring框架的基础上加入junit4, spring框架所需的jar包就不一一列出来了

2.生成一个junit的测试类

列如:我们现在对一个登陆功能业务的接口测试

1).找到你要测试的接口或者接口实现类

2)单击右键---->new---->other---->junit---->junit test case---->next---->选择即将生成的测试类所在的package(可选)---->next---->勾选要测试的方法(可选)---->finish

095400_X1dX_2357905.png

095403_gvdW_2357905.png

095406_FJmW_2357905.png

095408_X1nq_2357905.png

完成上面的步奏可以看到生成的测试类了

3.测试类的编码

1).测试类应该继承  AbstractJUnit4SpringContextTests或者AbstractTransactionalJUnit4SpringContextTests   

对于继承类的选择当测试类中需要用到事务管理时就用AbstractTransactionalJUnit4SpringContextTests 

 

 

 

2).在测试类前面加上

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations"file:WebContent/WEB-INF/autolinkedadmin-servlet.xml")

引入spring配置文件

 

3).junit4 执行 

右键方法名或者class 选择 Run As ----> junit test 

095559_n2Xr_2357905.png

 

095742_kr3h_2357905.png

 

结果断言预期值跟接口方法返回值不一致  测试失败:

结果断言预期值跟接口方法返回值一致 测试成功:

 

4.测试Controller (单元测试)编码

如何生成一个controller测试类在第二步已经介绍了,就不说了(也可以手动创建测试class)

1.首先在spring配置文件里面加入bean

<!-- junit4 测试Controller -->

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />  

<bean  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

 

2.new一个BaseControllerTest

 

public class BaseControllerTest {

private static HandlerMapping handlerMapping;  

    private static HandlerAdapter handlerAdapter;

    

    @BeforeClass  

    public static void setUp() {  

     if (handlerMapping == null) {

         String[] configs = {"file:WebContent/WEB-INF/autolinkedadmin-servlet.xml" };//这里配置文件根据实际项目相关

            XmlWebApplicationContext context = new XmlWebApplicationContext();

            context.setConfigLocations(configs);

            MockServletContext msc = new MockServletContext();

            context.setServletContext(msc);

            context.refresh();  

            msc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,context);

            handlerMapping = (HandlerMapping) 

              context.getBean(DefaultAnnotationHandlerMapping.class);  

            handlerAdapter = (HandlerAdapter) 

              context.getBean(context.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);

        }

    }  

 

    public ModelAndView excuteController(HttpServletRequest request, HttpServletResponse response)throws Exception {  

     request.setAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPINGtrue);    

     HandlerExecutionChain chain = handlerMapping.getHandler(request);  

            final ModelAndView model = handlerAdapter.handle(request, response,  

                    chain.getHandler());  

            return model;  

        }  

 

}

 

3.controller测试类

一下代码包括了 1.正常的跳转页面 2.模拟页面传入的参数 3.模拟session

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = "file:WebContent/WEB-INF/autolinkedadmin-servlet.xml")

public class UserControllerTest extends BaseControllerTest{

@Resource(name = "webSessionConstantMap")

protected Map<String, String> webSessionConstant; //模拟session时拿sessionkey(只在用到session时用,这里是根据spring注解拿的,实际情况跟项目走)

private static MockHttpServletRequest request = new MockHttpServletRequest();  

    private static MockHttpServletResponse responsenew MockHttpServletResponse();

    

@Test

public void testShowAdminUserLogin() throws Exception{

request.setCharacterEncoding("UTF-8");

request.setRequestURI("/showAdminUserLogin");//要测试方法的url

request.setMethod(HttpMethod.POST.name()); 

        //request.addParameter("login_userName", "admin123");

        //request.addParameter("login_userPassword", "admin123"); //模拟页面传入的参数(只在controller需要接收页面参数时用到)

        /*AdminUser user = new AdminUser();

        user.setId(1L);

        request.getSession().setAttribute(webSessionConstant.get("SESSION_USER"), user);*/ //模拟session(列如在跳转某些页面之前判断了是否登录,而登录的user对象放入了session,就在这里模拟session的登录状态)

        request.setMethod("POST");

        ModelAndView mav = this.excuteController(requestresponse);  

System.out.println(mav.getViewName());

        assertEquals("forward:/WEB-INF/jsp/adminUser/login.jsp", mav.getViewName()); //比较一下是否是自己预期要跳转的页面

}

 

}

 

转载于:https://my.oschina.net/u/2357905/blog/482036

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值