【问题标题】:Why spring test is fail, does not work @MockBean为什么弹簧测试失败,不起作用@MockBean
【发布时间】:2018-02-04 22:22:02
【问题描述】:

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

这是控制器:

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 参数 = {} 标头 = {Accept=[text/html]}

处理程序: 类型 = 空

异步: 异步启动 = false 异步结果 = null

已解决的异常: 类型 = 空

模型和视图: 视图名称 = null 视图 = 空 模型 = null

闪图: 属性 = null

MockHttpServlet响应: 状态 = 403 错误消息 = 访问被拒绝 标头 = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1;模式=块],缓存控制=[无缓存,无存储, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Strict-Transport-Security=[max-age=31536000 ; 包括子域]} 内容类型 = null 身体 = 转发 URL = null 重定向 URL = null 饼干 = []

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

【问题讨论】:

  • 你试过@MockMvc吗?有什么变化吗?
  • 错误就在那里。 : Status = 403 Error message = Access is denied Header。您需要提供安全凭据,或禁用它以进行单元测试。
  • @Darren Forsythe 是的,但我使用@WithMockUser(username = "user", roles = "user") 还不够吗?如何实施提供安全信用?我认为我的@WithMockUser 解决了。
  • @Reborn 在您发表评论后,我尝试将 @Autowired 替换为 @MockMvc,但我的 IDE 收到有关构造函数的警告消息。

标签: java spring spring-mvc spring-boot spring-test-mvc


【解决方案1】:

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

解决方案是导入您的 Spring Security 配置的 @Configuration 类,除了像 @Import(SecurityConfig.class) 这样声明 @WebMvcTest(ItemController.class)(假设您的 Spring Security 的自定义配置在一个名为SecurityConfig)。

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

另一个选项是禁用 Spring Security,如下所述:Disable security for unit tests with spring boot

【讨论】:

  • 我的错误@WithMockUser(username = "user", roles = "user") ->@WithMockUser(username = "user", roles = "USER") 也需要转换角色“user” CAPSLOOK .一切都好。
猜你喜欢
  • 1970-01-01
  • 2018-04-04
  • 2020-02-28
  • 2020-06-20
  • 1970-01-01
  • 2019-08-10
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多