Hi list,
does anybody know how to mock a SecurityContext which gets injected in a
Service Class exposed as Rest service in a junit test?
Here is the Service Class (the get method checks the currently logged in
user):
##################### ...
@Path("/user")
@Produces(MediaType.APPLICATION_JSON)
@Stateless
@Lock(LockType.READ)
public class UserService {
@Context
private SecurityContext context;
/**
* returns logged in user
*/
@Path("/get")
@GET
@Lock(LockType.WRITE)
public Response get() {
try {
User user = ((UserPrincipal)
context.getUserPrincipal()).getUser();
return Response.ok(getDefaultGson().toJson(user),
MediaType.APPLICATION_JSON_TYPE).build();
} catch (Exception e) {
logger.debug("no user principal in context");
return Response.status(Status.FORBIDDEN).build();
}
}
... #########################
the JUnit tests uses the ApplicationComposer and looks like this:
....#########################
@EnableServices(value = "jaxrs")
@RunWith(ApplicationComposer.class)
public class UserServiceTest {
@Module
@Classes(value = { UserService.class}, cdi = true) // scan these classes
public WebApp war() {
return new WebApp() // define rest Application
.contextRoot("UserServiceTest");
}
@Test
public void get() throws IOException, NamingException {
final Response message = WebClient.create("http://localhost:4204")
.path("/UserServiceTest/user/get").get(Response.class);
assertEquals(403, message.getStatus());
}
....###################
I tried several hours to find an example how to create a SecurityContext
mock in the test, which than is injected in the UserService with no luck.
I hope someone has a hint for me.
Uli