我有这样的测试:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@ActiveProfiles("test")
public class MyTests {
@Autowired
private TestRestTemplate restTemplate;
....
在测试中,我禁用了身份验证/授权
但在代码中我使用以下内容:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
但这就是测试失败的原因。
我如何模拟我的测试?
附言
这个不行:
@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()
在代码中返回 null
还有这个:
@Autowired
private TestRestTemplate restTemplate;
@Test
@WithMockUser(username = "aUser", roles = { "ADMIN" })
public void testUpdateWithoutNameAndEmail() {
...