本文介绍了为什么春季测试失败了,所以无法使用@MockBean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试为一个简单的spring-boot控制器创建我的第一个测试,但得到Handler: Type = null.在浏览器中,代码有效,但测试失败.我的应用程序使用spring-security.请帮助我解决问题并了解我的错误.谢谢.

I try to create my first the test for a simple spring-boot controller but I get Handler: Type = null. In browser code is work but a test fails. My App use spring-security. Please help me fix it an issue and understand my mistake. Thank You.

这是控制者:

private final ItemService service;

@GetMapping("/get_all_items")
public String getAllItems(Model model) {
    model.addAttribute("items", service.getAll());
    return "all_items";
}

这是一个测试.

@RunWith(SpringRunner.class)
@WebMvcTest(ItemController.class)
public class ItemControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private ItemService itemService;

    @Test
    @WithMockUser(username = "user", roles = "user")//mock security.
    public void whenGetAllItemsThenControllerReturnAllItems() throws Exception {
        given(
            itemService.getAll()
        ).willReturn(
                new ArrayList<Item>()
        );

        mvc.perform(
            get("/get_all_items").accept(MediaType.TEXT_HTML)
        ).andExpect(
                status().isOk()
        );
    }
}

这是结果日志:

处理程序: 类型= null

Handler: Type = null

异步: 异步开始=假 异步结果= null

Async: Async started = false Async result = null

已解决的异常: 类型= null

Resolved Exception: Type = null

ModelAndView: 视图名称=空 查看= null 型号=空

ModelAndView: View name = null View = null Model = null

FlashMap: 属性= null

FlashMap: Attributes = null

MockHttpServletResponse: 状态= 403 错误消息=访问被拒绝 标头= {X-Content-Type-Options = [nosniff],X-XSS-Protection = [1;模式=块],缓存控制= [无缓存,无存储, max-age = 0,必须重新验证],Pragma = [no-cache],Expires = [0], X-Frame-Options = [DENY],Strict-Transport-Security = [max-age = 31536000; includeSubDomains]} 内容类型=空 身体= 转发的网址=空重定向的网址=空 Cookies = []

MockHttpServletResponse: Status = 403 Error message = Access is denied Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Strict-Transport-Security=[max-age=31536000 ; includeSubDomains]} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = []

java.lang.AssertionError:预期状态:200实际:403

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

推荐答案

这本质上是一个重复的问题,已在此处回答: https ://stackoverflow.com/a/38676144/388980

This is essentially a duplicate question that has been answered here: https://stackoverflow.com/a/38676144/388980

解决方案除了为@WebMvcTest(ItemController.class)这样声明@WebMvcTest(ItemController.class)之外,还为Spring Security配置 import @Configuration(假定您对Spring Security的自定义配置位于名为的类中SecurityConfig).

The solution is to import the @Configuration class for your Spring Security configuration in addition to declaring @WebMvcTest(ItemController.class) like this @Import(SecurityConfig.class) (assuming your custom configuration for Spring Security is in a class named SecurityConfig).

您可能还会发现Spring Boot的问题跟踪器中的讨论也很有帮助: https://github.com/spring-projects/spring-boot/issues/6514

You might also find the discussion in Spring Boot's issue tracker helpful as well: https://github.com/spring-projects/spring-boot/issues/6514

另一种选择是禁用 Spring Security,如下所述:

The other option is to disable Spring Security as explained here: Disable security for unit tests with spring boot

这篇关于为什么春季测试失败了,所以无法使用@MockBean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:55