4

Let's say I have a method like the following:

@PreAuthorize("hasPermission(#obj, 'READ')")
public void requiresReadPermission(Object obj) {}

Is there an easy way to mock/grant/deny the "READ" permission for the authentication?

JWK
  • 670
  • 2
  • 6
  • 16

1 Answers1

0

Since it is a unit test of the method and not of the given interceptor, you do not need to bother with authentication and the ACL infrastructure. If you want to test that AccessDeniedException is thrown when a user is not granted access to the object, unit test the interceptor itself. In your case just test that your method does/returns what is expected to do/return.

If the authentication is not granted access to the given object, Spring Security ACL method interceptor throws AccessDeniedException as stated above and it is handled either in AccessDeniedHandler or in a catch block of a method calling directly or indirectly the secured method. If this is your situation, it is responsibility of the component depending on your secured method to handle the exception correctly.

The unit test for such a component could create the component with a mock of the component with secured method injected into it and simulate throwing AccessDeniedException. Then check that the exception is correctly handled.

pgiecek
  • 7,970
  • 4
  • 39
  • 47
  • 1
    I'm using JUnit 4, if during the unit test it doesn't return `AccessDeniedException` but in the real world it does, what is missing in configuring the unit test? – huahsin68 Apr 28 '14 at 14:26