Skip to content

Instantly share code, notes, and snippets.

@MrMjauh
Last active July 2, 2019 23:16
Show Gist options
  • Save MrMjauh/954c3a6c3f08d921eab5f019a7e1c3f4 to your computer and use it in GitHub Desktop.
Save MrMjauh/954c3a6c3f08d921eab5f019a7e1c3f4 to your computer and use it in GitHub Desktop.
AuthTest
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("prod")
public class AuthTest {
@MockBean
private IUserService userService;
@MockBean
private ITokenService tokenService;
@Autowired
private ObjectMapper mapper;
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mvc;
@BeforeEach
public void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).addFilter(new TokenAuthenticationFilter(tokenService)).build();
}
@AfterEach
public void cleanUp() {
reset(userService, tokenService);
}
@Test
public void getMe_ValidUser_ShouldReturnUser() throws Exception {
when(tokenService.getUserFromToken(any())).thenReturn(dummyUser());
when(userService.getUser(any())).thenReturn(dummyUser());
mvc.perform(get("/user").header(SecurityResource.X_AUTH_KEY, "dummy_token"))
.andExpect(content().string(dummyUserAsString()))
.andExpect(status().isOk());
}
@Test
public void getMe_NoValidUser_ShouldGiveBadRequestFromFilter() throws Exception {
when(tokenService.getUserFromToken(any())).thenReturn(null);
mvc.perform(get("/user").header(SecurityResource.X_AUTH_KEY, "dummy_token"))
.andExpect(content().string(genericErrorAsString()))
.andExpect(status().isBadRequest());
}
private User dummyUser() {
User user = new User();
user.setEmail("dummy@dummy.se");
user.setId(new ObjectId());
HashSet<String> roles = new HashSet<>();
roles.add(SecurityResource.Role.USER);
user.setRoles(roles);
return user;
}
private String dummyUserAsString() throws JsonProcessingException {
return mapper.writeValueAsString(UserDTO.from(dummyUser()));
}
private String genericErrorAsString() throws JsonProcessingException {
return mapper.writeValueAsString(Resource.GENERIC_ERROR);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment