@WebMVCTest中的404问题分析

Posted bladestone

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@WebMVCTest中的404问题分析相关的知识,希望对你有一定的参考价值。

问题分析

在创建单元测试Controller过程中,碰到了一个问题,具体如下:

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = 
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :200
Actual   :404

从结果信息来看,无法找到对应的MVC服务。

环境配置

Spring Boot 1.5.13, JDK 1.8
Controller示例代码如下:

import com.meituan.baobab.transport.supply.driver.manager.UserManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
public class MyController 
    public MyController() 
        log.info("init it");
    

    @RequestMapping("/hello")
    public String info() 
        return "hello, data";
    

    @Autowired
    private UserManager userManager;

    @RequestMapping(value="/users", method=RequestMethod.GET)
    public String hello(@RequestParam("info") String info) 
        log.info("Request Param:", info);
        String resultInfo = this.userManager.getMessage(info);

        log.info("resultInfo:", resultInfo);
        return resultInfo;
    

测试代码如下:

package com.meituan.baobab.transport.supply.driver.controller;

import cxxx.baseunit.TestWebConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.context.WebApplicationContext;

import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@Slf4j
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestWebConfig.class)
@WebMvcTest(controllers=MyController.class, secure=false)
public class MyControllerTest 
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @MockBean
    private UserManager userService;

    @MockBean
    private WhiteListDriverManager whiteListDriverManager;

    @Test
    public void testHello() throws Exception 
        when(userService.getMessage("world")).thenReturn("hello,world");

        MvcResult result = this.mockMvc.perform(get("/users?info=world")).andExpect(status().isOk()).andReturn();
        String resultInfo = result.getResponse().getContentAsString();
        log.info("resultInfo:", resultInfo);
        Assert.assertTrue("hello,world".equalsIgnoreCase(resultInfo));
    

    @Test
    public void testInfo() throws Exception 
        MvcResult result = this.mockMvc.perform(get("/hello")).andExpect(status().isOk()).andReturn();
    

解决方法

在class类之上,新增@ComponentScan注解,指定具体的扫描路径:

@Slf4j
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestWebConfig.class)
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class))
@WebMvcTest(controllers=MyController.class, WhiteListDriverController.class, secure=false)
public class MyControllerTest 
    @Autowired
    private MockMvc mockMvc;
    //..........

参考文档

  1. Allow @WebMvcTest without @SpringBootApplication
  2. Does @WebMvcTest require @SpringBootApplication annotation?

以上是关于@WebMVCTest中的404问题分析的主要内容,如果未能解决你的问题,请参考以下文章

@WebMvcTest 测试类中的 UnsatisfiedDependencyException

Spring Boot - 控制器测试失败并出现 404 代码

SpringBoot @WebMvcTest,自动装配 RestTemplateBuilder

@WebMvcTest 可以有两个控制器吗

使用@WebMvcTest 获取“必须存在至少一个 JPA 元模型”

是否可以在 WebMvcTest 中激活弹簧配置文件