我正在尝试为控制器编写测试用例。我不想模拟我的服务,因为我想将这些测试用作完整的功能测试。
我正在尝试测试这个控制器:
@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;
}
}
这是我写的测试用例:
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());
}
}
此测试用例失败,因为返回的 status() 是 404 而不是 200。不知道为什么它返回 404,因为 errorMessage 为 null。
我遇到过很多类似的问题,但没有一个对我有帮助。
配置错误。 为了解决这个问题,我必须在 contextConfiguration 中提供我的 WebConfig 文件。这是我添加的行:
@ContextConfiguration(classes = {WebConfig.class})
也许这取决于版本。我必须添加@Import(MyController.class)。结果:
@WebMvcTest(controllers = MyController.class)
@Import(MyController.class)
@ContextConfiguration(classes = {MyConfig.class})
class MyControllerTest {
}
我必须使用
standaloneSetup
。你可能想尝试一下。我还必须添加一个 viewResolver。我的代码看起来像这样。
我使用的是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());
}
}
我正在运行 Spring Boot 2.5.6,正在为我的控制器进行测试。有很多困难,因为 Spring 想要加载一些与安全相关的 bean。 最后,成功运行控制器测试,如下所示:
@WebMvcTest(controllers = AuthenticationController.class,
excludeAutoConfiguration = SecurityAutoConfiguration.class, // turn off websecurity (authorisation)
useDefaultFilters = false
)
@Import(AuthenticationController.class)
您的@EnableWebMvc可能未配置, 检查你的类路径中是否有任何类包含注释:
@EnableWebMvc
对于那些遇到同样问题但已经检查了所有配置的人,提示是:
通常,如果您想使用安全配置设置
@#WebMvcTest
,则不需要使用 @ContextConfiguration
,因为它可能会导致一些冲突,因此最安全的方法之一是使用 @Import
注释导入安全配置。例如:
@WebMvcTest(TaskController.class)
@Import(SecurityConfig.class)
class TaskControllerTest {
// ...
}
相关stackoverflow问题:@WebMvcTest需要@Import(SecurityConfig.class)来启用SpringSecurity
添加类注释 -
@WebMvcTest(PlanController.class)
它对我有用。