Spring 启动控制器在从注释测试调用时的行为有所不同@MvcTest



我在 Spring (2.0.5( 中有以下控制器

@RestController
public class FaqController {
@GetMapping("/faqs")
public void get(@RequestParam("language") final Locale locale) {
System.out.println(locale);
}
}

当我使用 url:http://localhost:8080/faqs?language通过邮递员/cURL 执行 GET 请求时,调用控制器方法并nulllocale

当我使用带注释@MvcTest JUnit 测试执行相同的 url 时,如下所示:

@RunWith(SpringRunner.class)
@WebMvcTest
public class FaqControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void test() throws Exception {
this.mockMvc.perform(get("/faqs?language"));
}
}

然后调用该方法,而是抛出org.springframework.web.bind.MissingServletRequestParameterException并显示消息:必需的区域设置参数"语言"不存在

为什么会有这种差异?我错过了什么吗?

你想让它为空吗?如果不需要,请将其删除或设置为"不需要"。

@RestController
public class FaqController {
@GetMapping("/faqs")
public void get(@RequestParam( value = "language", required = false ) final Locale locale) {
System.out.println(locale);
}
}

最新更新