junit+spring支持request,session,response等注入测试案例

此案例支持被测试的BEAN注入request response session,且可模拟测试。上代码:

package com.spl.savefe4wms.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.spl.savefe4wms.controller.UserController;
import com.spl.savefe4wms.dao.UserMapper;
import com.spl.savefe4wms.domain.User;
import com.spl.savefe4wms.log.tif.ILogService;
import com.spl.savefe4wms.service.IUserService;

/**
 * @author jdkleo
 *
 * 2015年11月18日
 */
@RunWith(value=SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(value="classpath:beans.xml")
public class UserTest {
	@Autowired
	MockHttpServletRequest request;
	
	@Autowired 
	MockHttpSession session;
	
	@Autowired 
	MockHttpServletResponse response;
	
	//--WEB模块测试
	@Autowired
	private UserController userController;
	
	//--业务模块测试
	@Autowired
	private IUserService userService;
	
	
	//--持久层测试
	@Autowired
	private UserMapper userDao;
	
	
	//--组件测试
	@Autowired
	private ILogService logService;
	
	
	@Test
	public void userController(){
		userController.init(request);
	}
	
	@Test
	public  void findAllUser() throws Exception {
		try {
			userService.findAllUser();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void find() {
		User user = userService.findById(1);
		System.out.println(user);
	}
	
	@Test
	@Transactional
	public void getUser() {
		User user = userDao.findById(1);
		System.out.println(user.getUsername());
	}
	
	@Test
	public void testLog(){
		session.setAttribute("test", "张三");
		logService.addSysLog("insert", "张三干坏事了");
	}
}

 

你可能感兴趣的:(junit+spring支持request,session,response等注入测试案例)