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

在练习 Springboot 2.x 搭建项目做 mock 测试时出现 404 错误,网上资料少且现有解决方法未解决。作者发现是因 @RequestMapping 和测试代码中地址未写“/”导致,建议统一写法以避免该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

练习Springboot2.x搭建项目的时候做mock测试报出如下错误:

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

网上资料不多,查找了几个解决方法并没有解决问题
简书上有一个是这样写的:
在这里插入图片描述
参考:简书:糖先生要健康生活的文章:spring boot mock mvc 404错误原因
我的错误是另外一个原因:
Controller代码:

@RestController
public class UserController {
    @RequestMapping("hello")
    public String hello(){
        return "hello world2";
    }
}

Test代码:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * @Author: lt
 * @Date: 2019/7/10 15:31
 */
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
  @Autowired
  private WebApplicationContext wac;


  private MockMvc mockMvc;

  @Before
  public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }

  @Test
  public void hello() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("hello").accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();
  }
}

因为习惯问题,@RequestMapping(“hello”)的地址会不写“/”,在测试 mockMvc.perform(MockMvcRequestBuilders.get(“hello”).accept(MediaType.APPLICATION_JSON))也没有写“/”
就是这个“/”导致了404

正确写法:

mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))

为了统一,建议@RequestMapping(“hello”)也写成:

@RequestMapping("/hello")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值