Spring Boot 版本:2.0.4.RELEASE
对于下面的 Spring Boot 测试,测试返回不需要的 401 响应:
“401”状态,“错误”:“未授权”
为测试禁用 Spring Security 的最佳方法是什么?
我尝试添加配置“security.basic.enabled=false”属性,如下所示:
@SpringBootTest(<br>
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,<br>
classes = TestApp.class,<br>
properties = {
"security.basic.enabled=false"
})
并将此注释添加到类中:
@AutoConfigureMockMvc(secure = false)
但不幸的是,测试仍然返回“401”未经授权的错误代码。
原始测试
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = App.class
)
public class ExampleTest{
@Autowired
public void setup(@LocalServerPort int port) {
RestAssured.port = port;
}
@Test
public voidtestMethod() {
// This test code is not important to my question.
given().log().all().get("/resources").then().log().all().statusCode(HttpURLConnection.HTTP_BAD_REQUEST).body("error", equalTo("invalid_request")).body(not(containsString("error_reason")));
}
}
被单元测试的类很简单:
@SpringBootApplication
@RestController
public class App {
@GetMapping("/resources")
public String[] resources(
@RequestParam("mandatory_param") String mandatory,
@RequestParam("valid_param") @NotNull String validParam) {
return new String[]{"1", "2"};
}
...
}
有谁知道如何为测试禁用弹簧安全性?谢谢