I have tests like 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 I disabled authentification/authorizaton
But in code I use following:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
But it is reason why tests fails.
How can I mock it my tests?
P.S.
This one 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 this one too:
@Autowired
private TestRestTemplate restTemplate;
@Test
@WithMockUser(username = "aUser", roles = { "ADMIN" })
public void testUpdateWithoutNameAndEmail() {
...
You can mock Spring's
Authentication
:And tell Spring's
SecurityContextHolder
to store thisAuthentication
instance:Now, if your code needs
Authentication
to return something (the user name perhaps) you just set some expectations on the mockedAuthentication
instance in the usual way e.g.There's also a Spring test annotation (
org.springframework.security.test.context.support.WithMockUser
) which does this for you...