简体   繁体   中英

How to parse JWT token in unit tests SpringBoot

I have a microservice setup with Spring boot and OAuth 2 with JWT. I have additional fields in my JWT token.

Most of my services call a static method that has a thread local of the additional fields in the token.
How can I write unit tests for such services?
Even if I tried to inject a mock user it doesn't work and I couldn't find a way of sending the JWT because I am no testing the controllers.

Code:

SecurityUtils static Calss (also check the package for other relevant JWT handler) .

Example on a method that will call the static class (Line 79) .

Method:

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);
}

I appreciate all the help.

Ok, so that's a common problem when using static methods. You can't easily override them, eg in tests. I think what I would do is to turn your SecurityUtils class into a service and make it implement an interface. Then inject this interface into any other service that needs to use it, instead of calling static methods. Then you can easily provide another implementation to your tests.

So you would have something like that:

interface SecurityUtils {
    String getUsername();
    ...
}

@Service
class MySecurityUtils immplements SecurityUtils {
    private JwtToken getJwtToken() {
        return MySecurityContextHolder.getContext().getJwtToken();
    }

    public String getUsername() {
        return getJwtToken().getUsername();
    }
    ...
}

Then in the unit test you can just inject a mock implementation of SecurityUtils to any class you're testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM