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


相关推荐

  • 认识 Iconfont 以及什么是 .eot、.woff、.ttf、.svg「建议收藏」

    认识 Iconfont 以及什么是 .eot、.woff、.ttf、.svg「建议收藏」一、Iconfont1.概述在前端作业中,二十年前只有页面中铺满文字就算上线产品,现如今,不加点俏皮的“图标”会让页面显得很Low很Low。图标在写这篇文章之前,我一直以为上图中的“图

    2022年8月5日
    3
  • 消息队列之事务消息,RocketMQ 和 Kafka 是如何做的?

    消息队列之事务消息,RocketMQ 和 Kafka 是如何做的?

    2020年11月20日
    208
  • 在 RT-Thread Nano 上添加控制台与 FinSH

    在 RT-Thread Nano 上添加控制台与 FinSH本片文档分为两部分:第一部分是实现UART控制台,该部分只需要实现两个数即可完成UART控制台打印功能。第二部分是实现移植FinSH组件,实现在控制台输入命令调试系统,该部分…

    2022年5月11日
    36
  • android 退出APP

    android 退出APP在onCreate()中将Activity实例放到线性容器中,,,,退出时,一顿((Activity)list.gert(i)).finsh();存在的问题也是很明显的。。。保存了Activity的引用,是否会涉及,内存回收的问题。。。。(你得直到下面用的是强引用的方式哦。)packagecom.mystore.customer.act

    2022年7月17日
    20
  • ByteBuffer的用法[通俗易懂]

    ByteBuffer的用法[通俗易懂]ByteBuffer也许很多人不常用,其实它是最常用的缓冲区,可以负责缓冲存储一段数据,供数据的写入和读取。ByteBuffer是NIO里用得最多的Buffer。ByteBuffer最核心的方法是put(byte)和get()。分别是往ByteBuffer里写一个字节,和读一个字节。值得注意的是,ByteBuffer的读写模式是分开的,正常的应用场景是:往ByteBuffer里写一些数

    2022年10月2日
    0
  • 0xc0000225无法进系统_win10系统出现0xc0000225无法进入系统的恢复方法

    0xc0000225无法进系统_win10系统出现0xc0000225无法进入系统的恢复方法win10系统出现0xc0000225无法进入系统的恢复方法?win10系统有很多人都喜欢使用,我们操作的过程中常常会碰到win10系统出现0xc0000225无法进入系统的问题。如果遇到win10系统出现0xc0000225无法进入系统的问题该怎么办呢?很多电脑水平薄弱的网友不知道win10系统出现0xc0000225无法进入系统究竟该怎么解决?其实不难根据下面的操作步骤就可以解决问题 第一步、…

    2022年6月26日
    46

发表回复

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

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