对具有依赖项TokenStore的类进行单元测试

时间:2019-05-08 08:38:51

标签: java junit

我想测试一个调用具有TokenStore依赖项的Static方法的类

当我运行测试TokenStore时会抛出空指针异常

如何避免引发空指针异常

@Component
public class TokenUtil {

private static TokenStore tokenStore;

@Autowired
public TokenUtil(TokenStore tokenStore) {
    TokenUtil.tokenStore = tokenStore;
}

public static OAuth2AccessToken getAccessToken() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Object details = authentication.getDetails();
    OAuth2AccessToken accessToken = null;
    if (details instanceof OAuth2AuthenticationDetails) {
        OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) details;

        String decodedDetails = oAuth2AuthenticationDetails.getTokenValue();

        accessToken = tokenStore.readAccessToken(decodedDetails);

    }
    return accessToken;
}
}

下面是我的测试代码

@Test
public void name() {
    Set<String> scopes = new HashSet<>();
    scopes.add("admin");
    OAuth2AccessToken oAuth2AccessToken = mock(OAuth2AccessToken.class);
    when(oAuth2AccessToken.getScope()).thenReturn(scopes);

    Authentication auth = mock(Authentication.class);
    SecurityContext secCont = mock(SecurityContext.class);
    TokenStore tokenStore = mock(TokenStore.class);
    OAuth2AuthenticationDetails oAuth2AuthenticationDetails = mock(OAuth2AuthenticationDetails.class);

    when(secCont.getAuthentication()).thenReturn(auth);
    SecurityContextHolder.setContext(secCont);
    when(auth.getDetails()).thenReturn(oAuth2AuthenticationDetails);
    when(oAuth2AuthenticationDetails.getTokenValue()).thenReturn("test");

    when(tokenStore.readAccessToken(anyString())).thenReturn(oAuth2AccessToken);
    TokenUtil.getAccessToken();
}

0 个答案:

没有答案
相关问题