且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Spring Boot测试类上使用@WebMvcTest批注时出错

更新时间:2022-01-04 03:14:24

@WebMvcTest#secure 属性是 true 默认情况下。如果你有 spring-security-test 作为测试依赖项,那么spring test将在测试期间生效(可以通过设置 WebMvcTest来关闭它#secure false )。但是,如果您的控制器使用身份验证或其主体,您可能会进行失败的测试。

The @WebMvcTest#secure property is true by default. If you have spring-security-test as a test dependency, then spring security will take affect during the test (which can be switched off by setting WebMvcTest#secure to false). However, if your controller is making use of Authentication or its principal, you'll probably have failing tests.

因此,您可以使用 @ org.springframework.security.test.context.support.WithMockUser 将使用用户名用户和密码密码创建经过身份验证的用户。这样做,您的测试不应再因为身份验证而失败(但可能需要授权)。

So, you can make use of @org.springframework.security.test.context.support.WithMockUser which will create an authenticated user with username user and password password. In doing so, your test should no longer fail because of authentication (but possibly with authorization).

我建议你看一下spring关于测试的文档这里

I suggest you take a look at spring's documentation about testing here.