springboot实战第四章-Spring MVC的测试

springboot实战第四章-Spring MVC的测试

Spring MVC的测试

本节主要是进行一些和Spring MVC相关的测试,控制器的测试

测试需要添加的依赖不必说了,已经在第一部分添加完毕,spring-test和junit两个依赖包

1.演示服务DemoService

package com.just.springmvc4.service;

import org.springframework.stereotype.Service;

@Service
public class DemoService {

    public String saySomething(){
        return "hello";
    }
}

2.普通控制器

返回一个页面

package com.just.springmvc4.controller;

import com.just.springmvc4.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class NormalController {
    @Autowired
    private DemoService demoService;
    @RequestMapping("/normal")
    public String testPage(Model model){
        model.addAttribute("msg",demoService.saySomething());
        return "page";
    }
}

page.jsp文件自己编写

3.RestController控制器

返回字符串

package com.just.springmvc4.controller;

import com.just.springmvc4.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {
    @Autowired
    private DemoService demoService;
    @RequestMapping(value = "/testRest",produces = "text/plain;charset=utf-8")
    public String testRest(){
        return demoService.saySomething();
    }
}

4.测试用例

在src/test/java下新建一个测试类

package com.just.springmvc4;

import com.just.springmvc4.config.MyMvcConfig;
import com.just.springmvc4.service.DemoService;
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.MockHttpServletRequest;
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.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyMvcConfig.class})
@WebAppConfiguration("src/main/resources")
public class TestControllerIntegration {
    /**
     * 模拟MVC对象
     */
    private MockMvc mockMvc;
    @Autowired
    private DemoService demoService;
    @Autowired
    private WebApplicationContext wac;
    @Autowired
    MockHttpSession session;
    @Autowired
    MockHttpServletRequest request;
    @Before
    public void setUp(){
        this.mockMvc= MockMvcBuilders.webAppContextSetup(this.wac).build();
    }
    @Test
    public void testNormalController() throws Exception {
        mockMvc.perform(get("/normal"))
                .andExpect(status().isOk())
                .andExpect(view().name("page"))
        .andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))
        .andExpect(model().attribute("msg",demoService.saySomething()));
    }
    @Test
    public void testRestController() throws Exception {
        mockMvc.perform(get("/testRest"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("text/plain;charset=utf-8"))
                .andExpect(content().string(demoService.saySomething()));
    }
}

@WebAppConfiguration注解在类上,用来声明加载的ApplicationContext是一个WebApplicationContext,它的属性指定的是资源的位置,默认为webapp,这里修改为本项目真正的资源目录

Others:

处理完这些再来一波编码过滤器,解决恶心的乱码问题,在配置文件中加入CharacterEncodingFilter,在request和response没有设置字符编码方式的时候设置一个编码方式

public class WebInitializer implements WebApplicationInitializer{
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //编码过滤器.控制所有请求
        CharacterEncodingFilter encodingFilter=new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        servletContext.addFilter("CharacterEncodingFilter",encodingFilter)
                .addMappingForUrlPatterns(null,false,"/*");           
        AnnotationConfigWebApplicationContext context=new AnnotationConfigWebApplicationContext();
        context.register(MyMvcConfig.class);
        context.setServletContext(servletContext);
        //注册DispatcherServlet
        ServletRegistration.Dynamic servlet=servletContext.addServlet("dispatcher",new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
        servlet.setAsyncSupported(true);  //开启异步方法的支持

    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/100309.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 华为云远程登录_华为云电脑如何远程连接电脑

    华为云远程登录_华为云电脑如何远程连接电脑引言最近在自己的华为云服务器上想装一个MySQL作为远程的数据库使用,数据库安装之后在本地访问远程数据库遇到了问题,一直报错10038,于是开始了漫长的翻帖爬楼的历程。在这里将这爬楼的历程记录下来。总的来说,(10038)错误有以下几种解决方式:1.mysql数据库user表的host由localhost改为%2.更改root用户的授权(与1相似)…

    2022年8月31日
    0
  • 什么是ARM?_arm开发板

    什么是ARM?_arm开发板原文一、ARM是什么?ARM既可以认为是一个公司的名字,也可以认为是对一类处理器的统称,还可以认为是一种技术的名字。ARM公司是专门从事基于RISC技术芯片设计开发的公司,作为知识产权供应商,本身不直接从事芯片生产,而是转让设计许可,由合作公司生产各具特色的芯片。ARM处理器的内核是统一的,由ARM公司提供,而片内部件则是多样的,由各大半导体公司设计,这使得ARM设计嵌入式系统的时候,可以基于同样的核心,使用不同的片内外设,从而具有很大的优势。二、ARM内核与架构

    2022年10月14日
    0
  • BetterIntelliJ 2021.4.4 激活码_通用破解码

    BetterIntelliJ 2021.4.4 激活码_通用破解码,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月17日
    95
  • 单片机交通信号灯控制系统设计_交通灯控制电路设计图

    单片机交通信号灯控制系统设计_交通灯控制电路设计图交通信号灯控制系统设计 作为一个硬件程序设计民工,最近一直在学习python,写个爬虫,排个序,再画个界面,其实还是挺好玩的。然而这不是我的主业啊!!!-_-|||下学期开学就要找工作了,明天刚好是新的一个月,还是滚回去调我的FPGA吧。今天先更新一个很小很小的例子作为开端,这是前几天xxx给我出的一道很随意的题目,主要是看面对一个项目…

    2022年9月24日
    0
  • navicat15 for mysql激活码【2021免费激活】「建议收藏」

    (navicat15 for mysql激活码)2021最新分享一个能用的的激活码出来,希望能帮到需要激活的朋友。目前这个是能用的,但是用的人多了之后也会失效,会不定时更新的,大家持续关注此网站~https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~14…

    2022年3月30日
    1.8K
  • c语言 hex转str 函数_int printf(const char)

    c语言 hex转str 函数_int printf(const char)voidhexDump(constchar*buf,intlen){ if(len<1||buf==NULL)return; constchar*hexChars="0123456789ABCDEF"; inti=0; charc=0x00; charstr_print_able[17]; charstr_hex_buffe…

    2022年9月21日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号