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


相关推荐

  • Java的输入输出语句_c语言有没有输入输出语句

    Java的输入输出语句_c语言有没有输入输出语句一、概述  输入输出可以说是计算机的基本功能。作为一种语言体系,java中主要按照流(stream)的模式来实现。其中数据的流向是按照计算机的方向确定的,流入计算机的数据流叫做输入流(inputStream),由计算机发出的数据流叫做输出流(outputStream)。Java语言体系中,对数据流的主要操作都封装在java.io包中,通过java.io包中的类可以实现计算机对数据的输入、输出操作…

    2022年4月19日
    41
  • 第一个模板类(templet<class elemType> class xxxxx)

    第一个模板类(templet<class elemType> class xxxxx)小弟是刚刚加入c++大队的,对c++中的基本知识只是稍微懂一点。今天在看《c++primer》中的模板类时,就将其中的程序在vs2008中写下,新建了Array.h和Array.cpp两个文件。主函数:Main.cpp1#include”stdafx.h”2#include<iostream>3#include”Array.h”45u…

    2022年5月19日
    55
  • java中=是啥意思?

    “=”表示赋值,是一个赋值运算符,可以将一个值赋给一个变量,如int a = 10;把字面量10赋值给整形变量a。

    2022年1月16日
    71
  • html css is图片,isbackground

    html css is图片,isbackgroundisbackground有何作用首先不是为了多线程而多线程,多线程会极大的带来额外的出错的几率。C#中第一个打开窗口的线程是主线程,也是处理UI的线程,最好保持这个线程通畅,即不要有阻塞操作,如Thread.Sleep(10);等这样是不好的。耗时的线程需要打开新的线程来操作。c#可以使用多少个Thread.IsBackground=true我现在有一个程序,有UDP/TCP/US…

    2022年10月16日
    2
  • linux 命令:whereis详解

    linux 命令:whereis详解linux命令:whereis详解

    2025年7月8日
    8
  • rsyslog接收远程日志_rsyslog接收远程日志

    rsyslog接收远程日志_rsyslog接收远程日志在另外一种环境中,让我们假定你已经在机器上安装了一个名为“foobar”的应用程序,它会在/var/log下生成foobar.log日志文件。现在,你想要将它的日志定向到rsyslog服务器,这可以通过像下面这样在rsyslog配置文件中加载imfile模块来实现。首先,加载imfile模块,这只需做一次。module(load=”imfile”PollingInterval=”5″)然后,指定…

    2022年9月24日
    2

发表回复

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

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