Spring Boot集成测试忽略了AutoConfigureMockMvc注释中的secure = false,得到401

Ada*_*dam 5 tdd spring-mvc spring-security spring-data-rest spring-boot

不能让我的@SpringBootTest工作.它说身份验证已启用,我不想要.

我已经设置好了 @AutoConfigureMockMvc(secure = false)

我提交了一个带有一些JSON的模拟请求,我的集成测试应该测试整个堆栈,通过Web层将SDR带到JPA然后进入内存数据库,这样我就可以使用它进行测试JdbcTemplate.

但响应是401,需要身份验证.为什么@AutoConfigureMockMvc(secure = false)不够?少了什么东西?

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        classes = { TestDataSourceConfig.class })
@EnableAutoConfiguration
@AutoConfigureMockMvc(secure = false)
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
@Transactional
public class SymbolRestTests  {

    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SymbolRepository symbolRepository;
    @PersistenceContext
    private EntityManager entityManager;  

    @Test
    public void shouldCreateEntity() throws Exception {

        String testTitle = "TEST.CODE.1";
        String testExtra = "Test for SymbolRestTests.java";
        String json = createJsonExample(testTitle, testExtra, true);
        log.debug(String.format("JSON==%s", json));
        MockHttpServletRequestBuilder requestBuilder =
                post("/symbols").content(json);
        mockMvc.perform(requestBuilder)
                .andExpect(status().isCreated())
                .andExpect(header().string("Location",
                        containsString("symbols/")));
        entityManager.flush();
        String sql = "SELECT count(*) FROM symbol WHERE title = ?";
        int count = jdbcTemplate.queryForObject(
                sql, new Object[]{testTitle}, Integer.class);
        assertThat(count, is(1));
    }
Run Code Online (Sandbox Code Playgroud)

输出记录:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /symbols
       Parameters = {}
          Headers = {}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

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

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 401
    Error message = Full authentication is required to access this resource
          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], 
                     WWW-Authenticate=[Basic realm="Spring"]}
         Content type = null
                 Body = 
        Forwarded URL = null
       Redirected URL = null
              Cookies = []
Run Code Online (Sandbox Code Playgroud)

我从401中的Spring Boot Integration Test Results中发现,我可以通过以下属性禁用安全性:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
    classes = { TestDataSourceConfig.class },
    properties = {
            "security.basic.enabled=false"
    })
Run Code Online (Sandbox Code Playgroud)

但是真的@AutoConfigureMockMvc(secure = false)应该有效,那阻止它的是什么?

Muh*_*der 12

亚当。

因为我最近也遇到了这个问题,更新后Spring Boot2.1.3.RELEASESpring Framework5.1.4.RELEASE,哪支部队还增加了Spring Web安全和如果有人想不提供安全解析那么他们需要禁用安全测试环境,所以我决定分享我是如何结束解决这个问题。

在开发应用程序和使用@SpringBootTest. 使用起来@WebMvcTest没有那么痛苦,tbh。

在我的情况下,以下工作。

@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)//This annotation was required to run it successfully
@DisplayName("UserControllerTest_SBT - SpringBootTest")
class UserControllerTest_SBT extends BaseTest_SBT {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void getUsersList() throws Exception {
        this.mockMvc.perform(MockMvcRequestBuilders.get("/user/listAll")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print());

    }

}

@ExtendWith(SpringExtension.class) //This is not mandatory
@SpringBootTest
@AutoConfigureMockMvc(secure = false) // Secure false is required to by pass security for Test Cases
@ContextConfiguration //This is also not mandatory just to remove annoying warning, i added it
public class BaseTest_SBT {

}
Run Code Online (Sandbox Code Playgroud)

什么不起作用:

1- @SpringBootTest(properties = {"security.basic.enabled=false"}) <-- 此解决方案已弃用!更多细节在这里

2 \src\test\resources\application.properties**-->security.basic.enabled=false

希望这会对某人有所帮助。


小智 9

改变

@AutoConfigureMockMvc(secure = false)
Run Code Online (Sandbox Code Playgroud)

@AutoConfigureMockMvc(addFilters=false)
Run Code Online (Sandbox Code Playgroud)

为我工作。

  • 这适用于“@WebMvcTest”测试,但不适用于“@SpringBootTest”测试。 (2认同)