@WithMockUser read value from static enum or string

Viewed 91

Inside the annotation of @WithMockUser, I would like read values from constant enum or string variables and lists.

For instance, let's assume that I have an enum like the following:

public enum RoleEnum {
    ROLE_ADMIN
    ROLE_MODERATOR,
    ROLE_USER;

    public static final String[] X_ROLE_GROUP = {ROLE_ADMIN.name(), ROLE_MODERATOR.name()};
}

I would like to use @WithMockUser by converting Enum values to String like this but the following syntax does not work:

@WithMockUser(roles = RoleEnum.ROLE_ADMIN.name())
@Test
public void test {
    ...
}

Is there a way that I could achieve this for single enum values and enum lists such as X_ROLE_GROUP?

1 Answers

Well, roles does not need the ROLE_ prefix, while authorities does. Annotation values are required to be compile-time constants. You can try this:

@Test
@WithMockUser(roles = Role.ROLE_ADMIN)
void test() {
}

public static final class Role {
    public static final String ROLE_ADMIN = "ADMIN";
    public static final String ROLE_MODERATOR = "MODERATOR";
    public static final String ROLE_USER = "USER";

    private Role() {
    }

    public static final String[] X_ROLE_GROUP = {
            ROLE_ADMIN,
            ROLE_MODERATOR
    };
}

Or if you want a mixin style (other classes can implement to inherit the constants), try:

public interface Role {
    String ROLE_ADMIN = "ADMIN";
    String ROLE_MODERATOR = "MODERATOR";
    String ROLE_USER = "USER";

    String[] X_ROLE_GROUP = {
            ROLE_ADMIN,
            ROLE_MODERATOR
    };
}
Related