gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:18:55 24 4
gpt4 key购买 nike

不能让我的 @SpringBootTest工作。它说身份验证已开启,这是我不想要的。

我已经设置了 @AutoConfigureMockMvc(secure = false)
我提交了一个带有一些 JSON 的模拟请求,我的集成测试应该测试整个堆栈,将它通过带有 SDR 的 Web 层传输到 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 Boot 2.1.3.RELEASE Spring Framework 5.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"}) <-- 此解决方案已弃用! More details here

2- \src\test\resources\application.properties** -> security.basic.enabled=false
希望这会对某人有所帮助。

关于spring-mvc - Spring Boot 集成测试忽略 AutoConfigureMockMvc 注释中的 secure=false,得到 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44412128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com