java - Test a Spring Controller with JUnit that depends of Spring Security -
i have spring application , building junit
tests test controller
.
the problem inside controller
call code:
final authentication authentication = securitycontextholder.getcontext().getauthentication(); final string username = authentication.getname();
in other words, need authenticate before calling controller
. wrote junit
test code:
private mockmvc mockmvc; @test public void getpagetest() throws exception{ final processfilecontroller controller = new processfilecontroller(); mockmvc = standalonesetup(controller).build(); mockmvc.perform(get(uri.create("/processfile.html")).sessionattr("freetrialemailaddress", "")).andexpect(view().name("processfile")); }
and when run gives me nullpointerexception
right on final string username = authentication.getname();
because authentication
null
since did not login.
the question is: there way mock authentication? ideas welcome.
thank you.
ideally use @authenticationprincipal
if isn't option need setup securitycontext
authentication
instance available in test.
you static method in helper class this.
public static void setupsecuritycontext(string username, string password, string... groups) { list<grantedauthority> authorities = new arraylist<>(); (string group : groups) { authorities.add(new simplegrantedauthority(group)); } userdetails user = new userdetails(username, password, authorities); usernamepasswordauthenticationtoken token = new usernamepasswordauthenticationtoken(user, password); securitycontextholder.getcontext().setauthentication(token); }
then in test can call
securityhelper.setupsecuritycontext("user", "password", "g1", "g2");
Comments
Post a Comment