itsource

AutoConfigureMockMvc 주석에서 secure=false를 무시하는 Spring Boot 통합 테스트에서 401을 얻습니다.

mycopycode 2023. 7. 21. 21:36
반응형

AutoConfigureMockMvc 주석에서 secure=false를 무시하는 Spring Boot 통합 테스트에서 401을 얻습니다.

만들 수 없습니다.@SpringBootTest작동합니다. 인증이 켜져 있다고 표시됩니다. 저는 원하지 않습니다.

로 설정했습니다.@AutoConfigureMockMvc(secure = false)

저는 몇몇 JSON과 함께 모의 요청을 제출하고 통합 테스트를 통해 전체 스택을 테스트해야 합니다. 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 = []

401의 Spring Boot Integration Test 결과를 통해 다음과 같은 속성을 통해 보안을 해제할 수 있음을 알게 되었습니다.

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

하지만 정말로@AutoConfigureMockMvc(secure = false)작동해야 하는데, 무엇이 그것을 막고 있나요?

변화하는

@AutoConfigureMockMvc(secure = false)

로.

@AutoConfigureMockMvc(addFilters=false)

저한테는 효과가 있어요.

아담

저도 최근 에 업데이트한 후 이 문제가 발생했기 때문에 Spring Web Security를 추가해야 하고 보안 확인기를 제공하지 않으려면 테스트 환경에서 보안을 해제해야 합니다. 그래서 어떻게 이 문제를 해결했는지 공유하기로 했습니다.

애플리케이션을 작성하고 통합 테스트 사례를 작성하는 동안에도 머리를 긁적이고 있었습니다. 사용하는 것은 이것보다 훨씬 덜 고통스럽습니다.

저의 경우 다음과 같은 작업이 수행되었습니다.

@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

바라건대, 이것이 누군가에게 도움이 되기를 바랍니다.

언급URL : https://stackoverflow.com/questions/44412128/spring-boot-integration-test-ignoring-secure-false-in-autoconfiguremockmvc-annot

반응형