JUnit下测试SpringMVC的Controller
废话少说,直接贴代码
EnumController
@Controller
@RequestMapping("/enum")
public class EnumController
{
@Autowired
private EnumService enumService;
@ResponseBody
@RequestMapping("/addtype")
public JSONResult addtype(HttpServletRequest request,HttpServletResponse response,
EnumType enumType){
Assert.notNull(enumType.getEnumNo(), "字典类别编号不能为空");
Assert.notNull(enumType.getEnumName(), "字典类型名称不能为空");
EnumType newType = enumService.addOrUpdateEnumType(enumType);
JSONResult result = new JSONResult(true, "", newType);
return result;
}
@ResponseBody
@RequestMapping("/updatetype")
public JSONResult updatetype(HttpServletRequest request,HttpServletResponse response,
EnumType enumType){
Assert.notNull(enumType.getId(), "字典类别ID不能为空");
Assert.notNull(enumType.getEnumNo(), "字典类别编号不能为空");
Assert.notNull(enumType.getEnumName(), "字典类型名称不能为空");
EnumType newType = enumService.addOrUpdateEnumType(enumType);
JSONResult result = new JSONResult(true, "", newType);
return result;
}
}
EnumControllerTest :
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
@Transactional
public class EnumControllerTest {
private static final Logger logger = LoggerFactory.getLogger(EnumControllerTest.class);
@Autowired
private WebApplicationContext wac;
@Autowired
private EnumController enumController;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(enumController).build();
}
@Test
@Rollback(true)
public void test_updatetype() throws Exception {
}
@Test
@Rollback(false) // 事务不回滚,数据更新至数据库中
public void test_addtype() throws Exception {
ResultActions ra = this.mockMvc.perform(MockMvcRequestBuilders
.post("/enum/addtype")
.accept(MediaType.APPLICATION_JSON)
.param("enumName", "测试1")
.param("enumNo", "test1"));
MvcResult mr = ra.andReturn();
String result = mr.getResponse().getContentAsString();
logger.info(result);
}
}