問題提出
在編寫單元測試過程中,碰到如下問題:
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;