首页 > 解决方案 > Spring REST Docs 配置不起作用 - java.lang.IllegalStateException

问题描述

@AutoConfigureRestDocs 和 @AutoConfigureMockMvc 没有正确配置 MockMvc。即使手动配置它们似乎也无济于事。

我也尝试手动配置 MockMvc 和 MockMvcRestDocumentationConfigurer,但没有帮助。

这是当前的设置:

@RunWith(SpringRunner.class)
@SpringBootTest(properties= "spring.main.allow-bean-definition-overriding=true")
@AutoConfigureRestDocs
@AutoConfigureMockMvc
public class LoginLogoutTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void adminCanLoginLogout() throws Exception {
        mockMvc.perform(formLogin().user(TestConfig.ADMIN_USERNAME).password(TestConfig.PASSWORD))
            .andExpect(status().isOk())
            .andExpect(authenticated().withUsername(TestConfig.ADMIN_USERNAME))
            .andDo(document("login"));

        mockMvc.perform(logout())
            .andExpect(status().isOk())
            .andExpect(unauthenticated())
            .andDo(document("logout"));
    }

}

我还尝试使用以下方式配置它们:

@RunWith(SpringRunner.class)
@SpringBootTest(properties= "spring.main.allow-bean-definition-overriding=true")
public class LoginLogoutTest {

    @Rule
    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");

    private MockMvc mockMvc;

    @Before
    public void setUp(){
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
          .apply(documentationConfiguration(this.restDocumentation))
          .build();
    }

    @Test
    public void adminCanLoginLogout() throws Exception {
        mockMvc.perform(formLogin().user(TestConfig.ADMIN_USERNAME).password(TestConfig.PASSWORD))
            .andExpect(status().isOk())
            .andExpect(authenticated().withUsername(TestConfig.ADMIN_USERNAME))
            .andDo(document("login"));

        mockMvc.perform(logout())
            .andExpect(status().isOk())
            .andExpect(unauthenticated())
            .andDo(document("logout"));
    }

}

我收到以下错误:

java.lang.IllegalStateException: REST Docs configuration not found. Did you forget to apply a MockMvcRestDocumentationConfigurer when building the MockMvc instance?

我究竟做错了什么?错误消息不是很丰富。

标签: javaspringspring-securityspring-testspring-restdocs

解决方案


推荐阅读