【发布时间】:2021-08-08 00:36:10
【问题描述】:
我有一个带有 Spring boot 的微服务设置和带有 JWT 的 OAuth 2。 我的 JWT 令牌中有其他字段。
我的大多数服务都调用一个静态方法,该方法具有令牌中附加字段的本地线程。
如何为此类服务编写单元测试?
即使我尝试注入一个模拟用户,它也不起作用,而且我找不到发送 JWT 的方法,因为我没有测试控制器。
代码:
SecurityUtils static Calss (also check the package for other relevant JWT handler) .
Example on a method that will call the static class (Line 79).
方法:
public CommonResponse saveUpdateProfile(ProfileRequest request) {
String authUsername = SecurityUtils.getUsername();
Optional<ProfileEntity> optionalProfile = findProfileByUsername(authUsername);
ProfileEntity profile;
if (optionalProfile.isPresent()) {
profile = optionalProfile.get();
} else {
profile = ProfileEntity.builder()
.username(authUsername)
.build();
}
profile.setFirstName(request.getFirstName());
profile.setLastName(request.getLastName());
ProfileEntity savedProfile = profileRepository.save(profile);
if (savedProfile == null) {
throw new RuntimeException("Failed to save user in database");
}
return CommonResponse.ok(savedProfile);
}
感谢所有帮助。
【问题讨论】:
-
你能显示一些相关的代码吗?您如何尝试注入用户。该静态方法的外观如何。它是如何从服务中调用的。测试的样子。这将有助于解决您的问题。现在有点太模糊了。
-
@MichalTrojanowski 是的,抱歉,我添加了 github 参考,我没有添加测试,但您可以在 github 中找到它们,测试实现了我之前从 SecurityContext 检索的方法,我不能'还没有找到 JWT 的方法
标签: java spring-boot oauth-2.0 jwt microservices