首页 文章

为什么spring test失败,@ MockBean不起作用

提问于
浏览
2

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

这是控制器:

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()
        );
    }
}

这是结果日志:

MockHttpServletRequest:HTTP方法= GET请求URI = / get_all_items参数= {} Headers = {Accept = [text / html]}处理程序:Type = null异步:Async started = false异步结果= null已解决异常:Type = null ModelAndView: View name = null View = null Model = null FlashMap:Attributes = null MockHttpServletResponse:Status = 403错误消息=拒绝访问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]}内容类型= null正文=转发的URL = null重定向的URL = null Cookies = [] java.lang.AssertionError:状态预期:200实际:403

1 回答

相关问题