Spring UnitTest Http Status 401问题解决
Posted bladestone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring UnitTest Http Status 401问题解决相关的知识,希望对你有一定的参考价值。
问题提出
在编写单元测试过程中,碰到如下问题:
MockHttpServletResponse:
Status = 401
Error message = Full authentication is required to access this resource
Headers = WWW-Authenticate=[Basic realm="Spring"], 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]
Content type = null
............
响应结果中出现了401, 应该是权限访问过程中的拦截所致。
环境配置
Spring Boot 1.5.13
JDK 1.8
在maven中增加了安全控制,例如:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
代码如下:
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
@Slf4j
public class UserControllerTest
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
public void helloTest() throws Exception
when(userService.getMessage("world")).thenReturn("hello,world");
MvcResult result = this.mockMvc.perform(get("/users?info=world")).andExpect(status().isOk()).andReturn();
String resultInfo = result.getResponse().getContentAsString();
log.info("resultInfo:", resultInfo);
Assert.assertTrue("hello,world".equalsIgnoreCase(resultInfo));
解决问题
方法1:
修改application.properties设置:
security.basic.enable=false
方法2:
@WebMvcTest(value = UserController.class, secure = false)
其定义如下:
/**
* If Spring Security's @link MockMvc support should be auto-configured when it is
* on the classpath. Defaults to @code true.
* @return if Spring Security's MockMvc support is auto-configured
*/
@AliasFor(annotation = AutoConfigureMockMvc.class, attribute = "secure")
boolean secure() default true;
以上是关于Spring UnitTest Http Status 401问题解决的主要内容,如果未能解决你的问题,请参考以下文章