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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 史上最全ASCII码对照表0-255(%d)

    史上最全ASCII码对照表0-255(%d)十进制代码 十六进制代码 MCS字符或缩写 DEC多国字符名 ASCII控制字符1 0 0 NUL 空字符 1 1 SOH 标…

    2022年6月24日
    55
  • 【Nginx安装】CentOS7安装Nginx及配置[通俗易懂]

    【Nginx安装】CentOS7安装Nginx及配置[通俗易懂]Nginx是一款轻量级的网页服务器、反向代理服务器。相较于Apache、lighttpd具有占有内存少,稳定性高等优势。**它最常的用途是提供反向代理服务。**安装在Centos下,yum源不提供nginx的安装,可以通过切换yum源的方法获取安装。也可以通过直接下载安装包的方法,**以下命令均需root权限执行**:首先安装必要的库(nginx中gzip模块需要zli…

    2022年5月6日
    42
  • 2017双11核心技术揭秘—双十一海量数据下EagleEye的使命和挑战[通俗易懂]

    2017双11核心技术揭秘—双十一海量数据下EagleEye的使命和挑战[通俗易懂]公众号推荐:公众号:VOA英语每日一听微信号:voahk01可长按扫码关注,谢谢

    2022年8月16日
    4
  • mesh和ADhoc区别[通俗易懂]

    mesh和ADhoc区别[通俗易懂]adhoc网络和无线Mesh网络都采用分布式、自组织的思想形成网络,网络每个节点都具备路由功能,随时为其他节点的数据传输提供路由和中继服务。adhoc网络主要侧重应用于移动环境中,确保网络内任意两个节点的可靠通信,网络内数据流可以包括语音、数据和多媒体信息。无线Mesh网络是一种无线宽带接入网络,利用分布式思想构建网络,让用户在任何时间、任何地点都可以对互联网进行高速无线访问,是由ADh…

    2025年6月23日
    1
  • 雅虎优化最佳实践

    雅虎优化最佳实践毕竟对于前端来说,优化是躲不开的主题。在看200(cache)和304区别的时候,翻到了雅虎这边归纳出来的准则,虽然是十多年前的东西了吧,但是还是具有参考价值的,因此在原文基础上我进行了一些归纳翻译。原文地址:https://developer.yahoo.com/performance/rules.html减少初始访问的请求数,多使用缓存尽量减少使用的组件种类,因为页面会花很多时间下载组件们。尽…

    2022年7月13日
    28
  • OSChina 周六乱弹 —— 人家过得是造儿童节,咱呢?[通俗易懂]

    2019独角兽企业重金招聘Python工程师标准>>>…

    2022年4月9日
    43

发表回复

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

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