[英]Spring Boot Microservices JUnit Test- java.lang.NullPointerException: Cannot invoke "org.springframework.http.ResponseEntity.getBody()"
[英]Spring Boot Microservices JUnit Test- Controller Test- JWT JwtGrantedAuthoritiesConverter Issue
我尝试在 Spring 引导微服务中使用 jwt 来实现一些 controller 测试。
当我运行如下所示的测试方法时,出现此错误
java.lang.NoClassDefFoundError: org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter
Caused by: java.lang.ClassNotFoundException: org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter
这是下面显示的代码片段。
@Test
public void test_WhenPlaceOrderWithWrongAccess_thenThrow403() throws Exception {
OrderRequest orderRequest = getMockOrderRequest();
MvcResult mvcResult
= mockMvc.perform(MockMvcRequestBuilders.post("/order/placeOrder")
.with(jwt().authorities(new SimpleGrantedAuthority("ADMIN"))) // HERE IS THE ERROR LINE
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(orderRequest))
).andExpect(MockMvcResultMatchers.status().isForbidden())
.andReturn();
}
即使我在订单服务的 pom.xml 中添加了spring-security-oauth2-resource-server
依赖,它也没有帮助我解决问题。
在订单服务的pom.xml中添加spring-security-oauth2-resource-server
依赖后出现如下问题。
java.lang.NoClassDefFoundError: org/springframework/security/oauth2/jwt/Jwt$Builder
Caused by: java.lang.ClassNotFoundException: org.springframework.security.oauth2.jwt.Jwt$Builder
我该如何解决这个问题?
这是示例的链接: Link
可能,您只需要依赖项
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
但不是spring-security-oauth2-resource-server
仔细检查是否正确声明了spring-security-oauth2-resource-server
依赖项:scope compile
(必须在runtime
和test
时存在)和5.2 或更高版本(之前没有JwtGrantedAuthoritiesConverter
)。 您可以将其作为spring-boot-starter-oauth2-resource-server
传递依赖项拉取。 所以基本上,检查:
spring-boot-starter-oauth2-resource-server
被声明为每个资源服务器模块的依赖@WebMvcTest
)和带有模拟身份验证的集成测试( @SpringBootTest
和@AutoConfigureMockMvc
)进行模拟很抱歉告诉你,但你的代码一团糟:
mvn install
模块。spring-boot-starter-oauth2-resource-server
(例如产品服务)@SpringBootTest
)编写到单元测试控制器(应该是@WebMvcTest
和@MockBean
依赖项)在要求我们查看您的代码之前清理您的烂摊子。
现在,我只能告诉您遵循这些教程。 它详细介绍了资源服务器安全配置和测试。 它还演示了如何使用注释代替jwt()
MockMvc 后处理器。 注释对我来说更具可读性,并且还可以在测试安全服务时设置安全上下文:
@WithMockJwtAuth("ROLE_USER")
@Test
public void test_WhenPlaceOrder_DoPayment_Success() throws Exception {
OrderRequest orderRequest = getMockOrderRequest();
MvcResult mvcResult
= mockMvc.perform(MockMvcRequestBuilders.post("/order/placeOrder")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(orderRequest))
).andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.