user3487063
user3487063

Reputation: 3682

mock currently logged-in user in liferay for a unit test

I'm new to liferay, I'm working on my first task. I've created a method to check if a given role/permission is assigned to a user.

I want to write a test class that checks if the given role is assigned to a current logged-in user? How can I mock a currently logged-in user in a unit test?

Thanks in advance

Upvotes: 0

Views: 506

Answers (1)

Ben VonDerHaar
Ben VonDerHaar

Reputation: 281

This approach will not always work, because you can be a part of a role that you do not have permission to view.

Instead, you can use RoleLocalServiceUtil and the methods therein to check role membership, and ResourcePermissionLocalServiceUtil to check permissions on a particular resource.


Update - In order to mock a user, you can use this snippet:

PrincipalThreadLocal.setName(user.getUserId());
PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);
PermissionThreadLocal.setPermissionChecker(permissionChecker);

Again, if the user is trying to check if they belong to a role, you may get an false negative if they do not have permission to view that role.

Upvotes: 1

Related Questions