如何对新的Keycloak身份验证器进行单元测试?

时间:2017-08-03 19:28:15

标签: unit-testing keycloak

我扩展了Keycloak附带的UsernamePasswordForm身份验证器。我正在寻找关于如何“单元”测试它的例子。

有没有人有例子? 或者也许指点我?

1 个答案:

答案 0 :(得分:0)

我的一位同事最终为我做了这项工作。他的策略很简单,但同时也很烦人。

public abstract class KeycloakTestBase {
    protected final KeycloakSession session = mock(KeycloakSession.class);
    protected final HttpRequest request = mock(HttpRequest.class);
    protected final RealmModel realm = mock(RealmModel.class);
    protected final UserProvider userProvider = mock(UserProvider.class);
    protected final UserCredentialManager userCredentialManager = mock(UserCredentialManager.class);
    protected final EventBuilder eventBuilder = mock(EventBuilder.class);
    protected final ThemeProvider themeProvider = mock(ThemeProvider.class);
    protected final Theme theme = mock(Theme.class);
    protected final KeycloakContext context = mock(KeycloakContext.class);

    protected KeycloakTestBase() {
        when(session.userLocalStorage()).thenReturn(userProvider);
        when(session.userCredentialManager()).thenReturn(userCredentialManager);
        when(session.getContext()).thenReturn(context);

        when(context.getRealm()).thenReturn(realm);

        when(realm.getLoginTheme()).thenReturn("ourtheme");

        when(eventBuilder.user(anyString())).thenReturn(eventBuilder);

        when(userProvider.getUserById(anyString(), eq(realm))).thenReturn(getRandomUser());

        when(session.getProvider(ThemeProvider.class, "extending")).thenReturn(themeProvider);

        try {
            when(themeProvider.getTheme(anyString(), any(Theme.Type.class))).thenReturn(theme);
            when(theme.getMessages(any(Locale.class))).thenReturn(new Properties());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected UserModel getRandomUser() {
        return spy(new InMemoryUserAdapter(session, realm, UUID.randomUUID().toString()));
    }
}

之后使用它作为编写新单元测试的基础。这个基类负责将大多数事物连接在一起并返回一些合理的默认值。

扩展基本密钥泄漏类的单元测试类的难点在于偶尔会遇到在密钥泄露代码中调用的一些静态方法。如果您很幸运,可以删除静态代码并将其作为依赖项传递。如果你不走运......那你就不走运了。然而,Haven遇到了不幸的情况。例如,我们有AuthenticationManagerHelper来缓解对静态AuthenticationManager类的调用。

public class AuthenticationManagerHelper {

    public AuthenticationManager.AuthResult authenticateIdentityCookie(KeycloakSession session, RealmModel realm, boolean checkActive) {
        return org.keycloak.services.managers.AuthenticationManager.authenticateIdentityCookie(session, realm, checkActive);
    }
}