spring mvc+junit

spring mvc 의 간단 한 단원 테스트, 말하자면 spring mvc 를 테스트 하 는 controller 입 니 다.
먼저 두 편의 댓 글 을 참고 하 세 요.
1.http://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles
2.http://spring.io/blog/2012/11/07/spring-framework-3-2-rc1-new-testing-features
실천:
UserController.java
package com.test.web;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.test.domain.User;
import com.test.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController{
	private static final String FILES_DIR="e:/";
	@Resource
	private UserService userService;
	@RequestMapping("/save")
	public String save(User user) {
		userService.save(user);
		return "result";
	}
	@RequestMapping("/getUser")
	public @ResponseBody User getUser(HttpServletRequest request,@RequestBody User user) {
		System.out.println("AAAAAAA::"+user);
		request.setAttribute("data1",user);
		return user;
	}
	@RequestMapping("/getUsers")
	public @ResponseBody List<User> getUsers(HttpServletRequest request,@RequestBody List<User> users) {
		System.out.println(users.getClass().getName());
		for (User user : users) {
			System.out.println("BBBBBBBB::"+user);
		}
		request.setAttribute("data2", users);
		return users;
	}
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String add(HttpServletRequest request,@RequestParam("file") MultipartFile file) {
		//System.out.println("real path::"+request.getServletContext().getRealPath("/"));
		String filename=file.getOriginalFilename();
		File tmpFile=new File(FILES_DIR+filename);
		if(filename!=null&&!file.isEmpty()){
			try {
				FileCopyUtils.copy(file.getBytes(), tmpFile);
				System.out.println("    ");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "result";
	}
	
}

2.UserControllerTest.java
package com.test.web;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.test.config.AppConfig;
import com.test.domain.User;
import com.test.util.JsonUtil;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={ AppConfig.class})
public class UserControllerTest {
	@Autowired
	private WebApplicationContext webApplicationContext;
	private MockMvc mockMvc;
	@Before
	public void init(){
		mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
	}
	@Test
	public void printBeans(){
		String[] beans=webApplicationContext.getBeanDefinitionNames();
		for (String bean : beans) {
			System.out.println(bean);
		}
	}
	/*              */
	@Test
	public void testSave() throws Exception {
		mockMvc.perform(post("/user/save").param("id", "123").param("username", "you")).andExpect(status().isOk()).andExpect(view().name("result"));
	}
	/*      JSON            */
	@Test
	public void testGet() throws Exception {
		mockMvc.perform(post("/user/getUser").contentType(JsonUtil.APPLICATION_JSON_UTF8).content(JsonUtil.convertObjectToJsonBytes(new User(22,"werwr")))).andExpect(status().isOk());
	}
	/*      JSON            */
	@Test
	public void testGetAll() throws IOException, Exception {
		List<User> list=new ArrayList<User>();
		list.add(new User(23,"   "));
		list.add(new User(25,"    "));
		mockMvc.perform(post("/user/getUsers").contentType(JsonUtil.APPLICATION_JSON_UTF8).content(JsonUtil.convertObjectToJsonBytes(list))).andExpect(status().isOk());
	}
	/*           */
	@Test
	public void testUpload() throws Exception{
		MockMultipartFile file = new MockMultipartFile("file", "orig.txt", null, "bar".getBytes());
		mockMvc.perform(fileUpload("/user/upload").file(file)).andExpect(status().isOk());
	}
}

이상 은 spring mvc 의 단원 테스트 의 가장 핵심 내용 과 예 를 들 어 가장 핵심 코드 를 붙 였 습 니 다.
전체 소스 코드:http://download.csdn.net/detail/xiejx618/7037623
스프링 준 it 도 붙 여 주세요.
package com.test.service;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.test.domain.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class UserServiceTest {
	@Configuration
	@ComponentScan(basePackages={"com.test.service"})
	static class ContextConfiguration {}
	@Resource
	private UserService userService;
	
	@Test
	public void testSave(){
		userService.save(new User(123,"xxx"));
	}

}

저작권 성명: 본 고 는 블 로 거들 이 창작 한 글 로 블 로 거들 의 허락 없 이 전재 할 수 없다.

좋은 웹페이지 즐겨찾기