JUnit下测试SpringMVC的Controller

本文介绍如何利用JUnit框架来测试SpringMVC中的Controller,包括实现方法和具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值