I have a respository method annotated with @Secured. I am trying to write a unit test for this method, but my test fails because I need authentication to call the method. The method itself, happens to be the save() method. The error I get when I call the method is:
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
I cannot test this method because it requires authentication, and I cannot save a user to authenticate against (I am using hsqldb) because I would need to call this method to save. Any advice on how to unit test a method annotated with @secured or how to mock the authentication.
It depends on what you want to test.
If you want to test business logic of your application without any security stuff, you can disable security altogether. Assuming that you use
SpringJunit4Runner, you can put security configuration into separate file and don’t include it into@ContextConfiguration.If you want to test authorization (e.g. correct work of
@Securedannotations), you can accessSecurityContextdirectly, bypassing all authentication-related stuff (in this case you can put authentication configuration into separate file and don’t load it as well):All you need is to put an appropriate
Authenticationobject intoSecurityContextHolder:Finally, if you want to test authentication, you can run the test with the database containing test data.