@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?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值