Spring Boot 集成测试忽略 AutoConfigureMockMvc 注释中的 secure=false,得到 401 [英] Spring Boot integration test ignoring secure=false in AutoConfigureMockMvc annotation, get 401
问题描述
无法让我的 @SpringBootTest
工作.它说身份验证已开启,这是我不想要的.
Can't make my @SpringBootTest
work. It says authentication is on, which I do not want.
我已经用 @AutoConfigureMockMvc(secure = false)
我提交了一个带有一些 JSON 的模拟请求,我的集成测试应该测试整个堆栈,将它通过带有 SDR 的 Web 层传输到 JPA,然后进入内存数据库,因此我可以使用 对其进行测试JdbcTemplate
.
I submit a mock request with some JSON and my integration test should test the whole stack, taking it through the web layer with SDR to JPA and then into the in-memory database, so I can test for it using JdbcTemplate
.
但是响应是401
,需要认证.为什么 @AutoConfigureMockMvc(secure = false)
不够用?缺少什么?
But the response is 401
, requires authentication. Why isn't the @AutoConfigureMockMvc(secure = false)
enough? What's missing?
@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 集成测试结果 401 中发现我可以通过以下属性禁用安全性:
I discovered from Spring Boot Integration Test Results in 401 that I can disable security via properties with this:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = { TestDataSourceConfig.class },
properties = {
"security.basic.enabled=false"
})
但实际上 @AutoConfigureMockMvc(secure = false)
应该可以工作,那么是什么阻止了它?
but really the @AutoConfigureMockMvc(secure = false)
should work, so what's blocking it?
推荐答案
Adam.
因为我最近在将 Spring Boot
更新到 2.1.3.RELEASE
后也遇到了这个问题,并且Spring Framework
到 5.1.4.RELEASE
,强制添加 Spring Web Security,如果有人不想提供安全解析器然后他们需要在测试环境中禁用安全性,所以我决定分享我最终如何解决这个问题.
Since I also recently ran into this problem after updating Spring Boot
to 2.1.3.RELEASE
and Spring Framework
to 5.1.4.RELEASE
, which forces to add Spring Web Security and If someone wants to not provide security resolver then they are required to disable security in Test Environment, so I decided to share how I ended up resolving this issue.
在开发应用程序和使用 @SpringBootTest
编写集成测试用例时,我也在挠头.使用 @WebMvcTest
比这更痛苦,tbh.
I was also scratching head while working up an application and writing Integration Test Cases with @SpringBootTest
. Using @WebMvcTest
is way less painful than this, 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
希望这对某人有所帮助.
Hopefully, this will be helpful to someone.
这篇关于Spring Boot 集成测试忽略 AutoConfigureMockMvc 注释中的 secure=false,得到 401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!