殷建卫

海阔凭鱼跃,天高任鸟飞

Spring自带mock测试Controller

准备SpringMVC环境

注意:使用mock测试需要引入spring-test包

Base类:加载配置文件

package com.wyy.snail.user.controller;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = { "classpath:config/spring/spring-*.xml",
		"classpath:config/spring/service-mybatis.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseControllerTest extends AbstractTransactionalJUnit4SpringContextTests {
	
}

测试类:具体业务

package com.wyy.snail.user.controller;

import java.io.IOException;

import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

public class LoginControllerTest extends BaseControllerTest {

	@Test
	public void testLogin() throws IOException {
		LoginController loginController = (LoginController) this.applicationContext.getBean("loginController");
		MockHttpServletRequest request = new MockHttpServletRequest();
		MockHttpServletResponse response = new MockHttpServletResponse();
		request.setMethod("POST");
		request.addParameter("username", "aa");
		request.addParameter("password", "bb");
		loginController.login(request, response, "", "", "");
	}

}


阅读更多
个人分类: Spring开源框架
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭