java - How to mock security context in tests if I disabled authorizarion -
i have tests this:
@runwith(springrunner.class) @springboottest(webenvironment = springboottest.webenvironment.random_port) @dirtiescontext(classmode = dirtiescontext.classmode.before_class) @activeprofiles("test") public class mytests { @autowired private testresttemplate resttemplate; .... in tests disabled authentification/authorizaton
but in code use following:
authentication authentication = securitycontextholder.getcontext().getauthentication(); but reason why tests fails.
how can mock tests?
p.s.
this 1 doesn't work:
@test public void testupdatewithoutnameandemail() { authentication authentication = mockito.mock(authentication.class); securitycontext securitycontext = mockito.mock(securitycontext.class); mockito.when(securitycontext.getauthentication()).thenreturn(authentication); securitycontextholder.setcontext(securitycontext); mockito.when(authentication.getname()).thenreturn("aname"); resttemplate.exchange(.. securitycontextholder.getcontext().getauthentication() returns null in code
and 1 too:
@autowired private testresttemplate resttemplate; @test @withmockuser(username = "auser", roles = { "admin" }) public void testupdatewithoutnameandemail() { ...
you can mock spring's authentication:
authentication authentication = mockito.mock(authentication.class); and tell spring's securitycontextholder store authentication instance:
securitycontext securitycontext = mockito.mock(securitycontext.class); mockito.when(securitycontext.getauthentication()).thenreturn(auth); securitycontextholder.setcontext(securitycontext); now, if code needs authentication return (the user name perhaps) set expectations on mocked authentication instance in usual way e.g.
mockito.when(authentication.getname()).thenreturn("aname"); there's spring test annotation (org.springframework.security.test.context.support.withmockuser) you...
@test @withmockuser(username = "auser", roles = { "anauthority" }) public void atest(){ // usage of `authentication` in test instance withe user name "auser" , granted authority "anauthority" // ... }
Comments
Post a Comment