Anthony Raj S wrote:when I call this method in a normal way (not testing), the PreAuthorize is verified.
Yup and integration testing is where I think this stuff should be verified.
Then in my TestNG test I'd like to call this method and ensure that the PreAuthorize condition is verified.
What I was saying is by unit testing this method on its PreAuthorize conditions you are mostly just testing the framework. Typically you would unit test what the method does and test the security layer as part of your integration testing. Now as I said before, yes it can be done. I assume you are using SpringJunit runner, and the Spring support classes but you did not post any test code so I cannot tell for sure. Make sure that load all of the Spring Security Configuration needed to initialize the @PreAuthorize annotations correctly. and in a @Before block (or just sometime before you invoke the method) make sure you get your set an authenticated authentication token on the SecurityContextHolder. Now whether you want to do this like below or call embedded ldap or something else is up to you.
It might look something like this:
that said the exception that you have to handle if the user does not have the proper authority is usually a AccessDeniedException.
I don't use TestNG but whatever testing framework you decide to use should be fine.
I hope that helps you but my original point still stands. I don't see a point in writing unit tests like this, I think it should be tested as part of integration testing. Security is a cross cutting concern.