16-SpringBoot——Spring MVC基础-测试

Spring MVC基础-测试


【博文目录>>>】


【项目源码>>>】


【测试】


测试是保证软件质量的关键,为了测试Web 项目通常不需要启动项目,我们需要一些Servlet 相关的模拟对象,比如:MockMVC 、MockHttpServletRequest 、MockHttpServletResponse 、MockHttpSession 等。在Spring 里,我们使用@WebAppConfiguration 指定加载的ApplicationContext 是一个WebApplicationContext 。通过他来模拟一个web测试环境。Spring提供了非常丰富的测试功能。本例就演示如何使用Spring测试。

【代码实现】

package com.example.spring.framework.test.service;

import org.springframework.stereotype.Service;

/**
 * Author: 王俊超
 * Date: 2017-07-14 08:14
 * All Rights Reserved !!!
 */
@Service
public class DemoService {
    public String saySomething() {
        return  "hello";
    }
}
package com.example.spring.framework.test.controller;

import com.example.spring.framework.test.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;

/**
 * Author: 王俊超
 * Date: 2017-07-14 20:42
 * All Rights Reserved !!!
 */
@Controller
public class NormalController {
    @Autowired
    DemoService demoService;

    @RequestMapping(value = "/normal", produces = "text/plain;charset=UTF-8")
    public String testPage(Model model) {
        model.addAttribute("msg", demoService.saySomething());

        return "page";
    }
}
package com.example.spring.framework.test.controller;

import com.example.spring.framework.test.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Author: 王俊超
 * Date: 2017-07-14 20:45
 * All Rights Reserved !!!
 */
@RestController
public class MyRestController {

    @Autowired
    DemoService demoService;

    @RequestMapping(value = "/testRest", produces = "text/plain;charset=UTF-8")
    public @ResponseBody String testRest() {
        return demoService.saySomething();
    }
}
package com.example.spring.framework.test.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * Author: 王俊超
 * Date: 2017-07-14 08:15
 * All Rights Reserved !!!
 */
@Configuration
@EnableWebMvc
@EnableScheduling
@ComponentScan("com.example.spring.framework.test")
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);

        return viewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
        super.addResourceHandlers(registry);
    }


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/see").setViewName("/see");
        registry.addViewController("/async").setViewName("/async");
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Test page</title>
</head>
<body>
<pre>
    Welcome to Spring MVC world
</pre>
</body>
</html>
package com.example.spring.framework.test;

import com.example.spring.framework.test.config.MyMvcConfig;
import com.example.spring.framework.test.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.SpringRunner;
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.*;

/**
 * 1、@WebAppConfiguration 注解在类上,用来声明加载的ApplicationContex 是一个WebApplicationContext
 * 它的属性指定的是Web 资源的位置,默认为src/main/webapp ,本例修改为src/main/resources
 * 2、MockMvc模拟MVC对象
 * 3、可以在测试用例中注入Spring 的Bean
 * Author: 王俊超
 * Date: 2017-07-14 08:17
 * All Rights Reserved !!!
 */
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyMvcConfig.class)
@WebAppConfiguration("src/main/resources")
public class TestControllerIntegrationTests {
    private MockMvc mockMvc;

    @Autowired
    private DemoService demoService;

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    MockHttpSession session;

    @Autowired
    private MockHttpServletRequest request;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(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()));
    }
}

【运行结果】

这里写图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值