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

问题描述 投票:5回答:1

不能让我的@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));
    }

输出记录:

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 = []

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

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

但真的@AutoConfigureMockMvc(secure = false)应该工作,所以什么阻止它?

spring-mvc spring-boot spring-security tdd spring-data-rest
1个回答
2
投票

亚当。

因为我最近在将Spring Boot更新到2.1.3.RELEASESpring Framework5.1.4.RELEASE之后遇到了这个问题,强制添加Spring Web Security,如果有人不想提供安全解析器,那么他们需要在测试环境中禁用安全性,所以我决定分享我最终如何解决这个问题。

在编写应用程序并使用@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 {

}

什么行不通:

1- @SpringBootTest(properties = {"security.basic.enabled=false"})

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

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

© www.soinside.com 2019 - 2024. All rights reserved.