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() {
...
SecurityContextHolder.getContext().setAuthentication()
and pass to it someAuthentication
mock (or a real instance if you want) – Shirberg@SpringBootTest
annotation, a TestRestTemplate is automatically available and can be@Autowired
into your test. If you need customizations (for example to adding additional message converters) use a RestTemplateBuilder@Bean
." So build a TestRestTemplare with some authentication (username / password) – Shirberg