java MockMvc 返回 404 状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37775226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:47:15  来源:igfitidea点击:

MockMvc returning 404 status

javaspringjunitmockmvc

提问by Gaurav Kumar Singh

I am trying to write test cases for controller. I do not want to mock out my service as I would like to use these tests as complete functionality tests.

我正在尝试为控制器编写测试用例。我不想模拟我的服务,因为我想将这些测试用作完整的功能测试。

I am trying to test this controller:

我正在尝试测试这个控制器:

@Controller
public class PlanController {

     @Autowired
     private PlanService planService;

     @RequestMapping(
        value = "/api/plans/{planId}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
     @ResponseBody
     @Nonnull
     @JsonView(Plan.SimpleView.class)
     public Plan getPlan(@RequestParam int orgId, @PathVariable int planId) {
         Plan plan = planService.getPlan(orgId, planId);
         return plan;
    }
}

and Here is test case I have written:

这是我写的测试用例:

package com.videology.skunkworks.audiencediscovery.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.eclipse.jetty.webapp.WebAppContext;  
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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 org.springframework.web.servlet.config.annotation.EnableWebMvc;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class})
@WebAppConfiguration
@EnableWebMvc
public class PlanControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    }

    @Test
    public void testGetPlan() throws Exception {
        mockMvc.perform(get("/api/plans/1/?orgId=1").accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk());
    }
}

This test case is failing because status() being returned is 404 not 200. Not sure why it is returning 404 as errorMessage is null.

此测试用例失败,因为返回的 status() 是 404 而不是 200。不确定为什么它会返回 404,因为 errorMessage 为空。

I have been through many similar questions but None of them were helpful for me.

我遇到过很多类似的问题,但没有一个对我有帮助。

回答by Gaurav Kumar Singh

Error was in configuration. To Fix this, I had to provide my WebConfig file in contextConfiguration. Here is line I added:

错误是在配置中。为了解决这个问题,我必须在 contextConfiguration 中提供我的 WebConfig 文件。这是我添加的行:

@ContextConfiguration(classes = {WebConfig.class})

回答by Tony Zampogna

I had to use the standaloneSetup. You may want to try that. I also had to add a viewResolver. My code looks something like this.

我不得不使用standaloneSetup. 您可能想尝试一下。我还必须添加一个 viewResolver。我的代码看起来像这样。

I'm using SpringBoot 1.5.

我正在使用 SpringBoot 1.5。

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
    FilterChainProxy.class,
    HomeController.class
})
@WebAppConfiguration
public class HelloWorldTest {

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    private MockMvc mvc;


    @Before
    public void setup() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/templates/");
        viewResolver.setSuffix(".ftl");

        mvc = MockMvcBuilders
                .standaloneSetup(new HomeController())
                .setViewResolvers(viewResolver)
                .alwaysDo(print())
                .build();
    }


    @Test
    public void test() throws Exception {
        MvcResult result = mvc.perform(get("/home")
                .with(anonymous()))
                .andExpect(status().is2xxSuccessful())
                .andReturn();

        assertEquals("home", result.getModelAndView().getViewName());
    }
}

回答by Khairul Bashar Lemon

Your @EnableWebMvc may not configured, Check it in your classpath is there any class contains annotation:

您的 @EnableWebMvc 可能未配置,请在您的类路径中检查它是否有任何类包含注释:

@EnableWebMvc