spring mvc controller 层单元测试 demo

其他技术

2017-12-28

336

0

技术:spring 4.3.4-RELEASE

运行环境:IDEA 15.2 + jdk8 + windows 7

demo功能:提供一个调试spring mvc 控制器的 demo代码(代码不能直接运行, 请自行拷贝使用)

controller源代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by li_wb on 2017/10/25.
 * 包车查询页, 第一个页面, 下一个是 ListPageController 列表页
 */
@RequestMapping("/indexPage")
@RestController
public class IndexPageController extends BaseController {
    @Autowired
    private IIndexPageViewService service;

    //查询页初始化
    @RequestMapping("/init")
    @LogInAndOutAspectable(clazzName = IndexPageController.class)
    public ReturnMsgVo initIndexPage() {
        InitInput input = this.getPostObj(InitInput.class);
        return service.init(input);
    }
}

测试源代码

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:spring/spring-context.xml", "classpath:spring/spring-mvc.xml"})//对应的spring 配置文件
public class IndexPageControllerTester extends BaseControllerTester {
    @Autowired
    protected WebApplicationContext wac;

    protected MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = webAppContextSetup(this.wac).build();
    }

    //初始化插查询页数据 默认城市应该返回输入参数中的城市
    @Test//pass
    public void init1() throws Exception {
        InitInput input = mockInitInput();
        MvcResult result = mockMvc.perform((post("/indexPage/init")
                .content(JsonUtils.toJson(input))
                .cookie(mockCookie())
                .headers(mockHeaders())
                .contentType(MediaType.APPLICATION_JSON)
        )).andExpect(status().isOk()).andReturn();
        String content = result.getResponse().getContentAsString();
        printString(content);
        Assert.assertEquals(true, !StringUtils.isNullOrEmpty(content));
    }

}

目录结构

 

依赖

 
 

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think