本文整理汇总了Java中org.springframework.security.test.context.support.WithMockUser类的典型用法代码示例。如果您正苦于以下问题:Java WithMockUser类的具体用法?Java WithMockUser怎么用?Java WithMockUser使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
WithMockUser类属于org.springframework.security.test.context.support包,在下文中一共展示了WithMockUser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testFindClients
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@WithMockUser("user123")
public void testFindClients() throws Exception {
final OAuth2ClientEntity client = new OAuth2ClientEntity()
.setId("client123")
.setName("client")
.setDescription("description")
.setClientSecret("123456secret")
.setSecretRequired(true)
.setAutoApprove(false)
.setAuthorizedGrantTypes(new HashSet<>(Arrays.asList(AUTHORIZATION_CODE, IMPLICIT)));
Page<OAuth2ClientEntity> clients = new PageImpl<>(Arrays.asList(client));
when(oAuth2ClientService.findClients(anyString(), any())).thenReturn(clients);
MockHttpServletRequestBuilder request = get("/api/clients")
.contentType(MediaType.APPLICATION_JSON);
MockHttpServletResponse response = mockMvc.perform(request)
.andExpect(status().isOk())
.andDo(document("client-read-all"))
.andReturn()
.getResponse();
assertThat(response.getContentAsByteArray())
.isEqualTo(objectMapper.writeValueAsBytes(
clients.map(c -> OAuth2ClientRestData.builder().fromOAuth2ClientEntity(c).build())));
verify(oAuth2ClientService).findClients(anyString(), any());
}
示例2: updateNonExistingTask
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@Transactional
@WithMockUser(username="[email protected]",authorities={"ROLE_ADMIN"}, password = "admin")
public void updateNonExistingTask() throws Exception {
int databaseSizeBeforeUpdate = taskRepository.findAll().size();
// Create the Task
// If the entity doesn't have an ID, it will be created instead of just being updated
restTaskMockMvc.perform(put("/api/tasks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(task)))
.andExpect(status().isCreated());
// Validate the Task in the database
List<Task> taskList = taskRepository.findAll();
assertThat(taskList).hasSize(databaseSizeBeforeUpdate + 1);
}
示例3: testChangePasswordEmpty
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@Transactional
@WithMockUser("change-password-empty")
public void testChangePasswordEmpty() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password-empty");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password").content(RandomStringUtils.random(0)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
示例4: testChangePasswordTooSmall
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@Transactional
@WithMockUser("change-password-too-small")
public void testChangePasswordTooSmall() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password-too-small");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change_password").content("new"))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
示例5: successfulRefreshTokenWithAdminRole
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@WithMockUser(roles = "ADMIN")
public void successfulRefreshTokenWithAdminRole() throws Exception {
Authority authority = new Authority();
authority.setId(1L);
authority.setName(AuthorityName.ROLE_ADMIN);
List<Authority> authorities = Arrays.asList(authority);
User user = new User();
user.setUsername("admin");
user.setAuthorities(authorities);
user.setEnabled(Boolean.TRUE);
user.setLastPasswordResetDate(new Date(System.currentTimeMillis() + 1000 * 1000));
JwtUser jwtUser = JwtUserFactory.create(user);
when(this.jwtTokenUtil.getUsernameFromToken(any())).thenReturn(user.getUsername());
when(this.userDetailsService.loadUserByUsername(eq(user.getUsername()))).thenReturn(jwtUser);
when(this.jwtTokenUtil.canTokenBeRefreshed(any(), any())).thenReturn(true);
this.mvc.perform(get("/refresh"))
.andExpect(status().is2xxSuccessful());
}
开发者ID:adriano-fonseca,项目名称:rest-api-jwt-spring-security,代码行数:27,代码来源:AuthenticationRestControllerTest.java
示例6: testChangePassword
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@Transactional
@WithMockUser("change-password")
public void testChangePassword() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password").content("new password"))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("change-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue();
}
示例7: testChangePasswordTooLong
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@Transactional
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password-too-long");
user.setEmail("[email protected]");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change_password").content(RandomStringUtils.random(101)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
示例8: testFilter_withValidNotesPostCall_shouldSendEncryptedNote
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@WithMockUser(username="[email protected]",authorities={"ADMIN","AUTHOR"},password="none")
public void testFilter_withValidNotesPostCall_shouldSendEncryptedNote() throws Exception {
String validPost = "{\"title\":\"new note\",\"lastEdit\":\"2012-12-12T12:12:12Z\",\"pinned\":false,\"archived\":false,\"content\":\"very very secret text\",\"userId\":1}";
notesMock.stubFor(post(urlEqualTo("/api/v1/notes")).withRequestBody(equalToJson(validPost)).willReturn(aResponse().withStatus(200)));
AuthUserResponse response = new AuthUserResponse();
response.setCryptKey("sikdfyh089oay3i3ip2wr3o2rj3wio8yf");
when(userService.getUserInfoFromAuthEmail(matches("[email protected]"))).thenReturn(response);
String encryptedMessage = "{\"title\":\"new note\",\"lastEdit\":\"2012-12-12T12:12:12Z\",\"pinned\":false,\"archived\":false,\"content\":\"some text\",\"userId\":1}";
when(encryptionService.encryptNote(any(), matches(response.getCryptKey()),any()))
.thenReturn(new ByteArrayInputStream(encryptedMessage.getBytes()));
MvcResult result =
mockMvc.perform(post("/api/v1/notes").content(encryptedMessage).contentType(jsonContentType).with(csrf())).andReturn();
assertEquals("correct response returns 200", 200, result.getResponse().getStatus());
verify(encryptionService,times(1)).encryptNote(any(), any(),any());
}
示例9: createTask
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@Transactional
@WithMockUser(username="[email protected]",authorities={"ROLE_ADMIN"}, password = "admin")
public void createTask() throws Exception {
int databaseSizeBeforeCreate = taskRepository.findAll().size();
// Create the Task
restTaskMockMvc.perform(post("/api/tasks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(task)))
.andExpect(status().isCreated());
// Validate the Task in the database
List<Task> taskList = taskRepository.findAll();
assertThat(taskList).hasSize(databaseSizeBeforeCreate + 1);
Task testTask = taskList.get(taskList.size() - 1);
assertThat(testTask.getTitle()).isEqualTo(DEFAULT_TITLE);
assertThat(testTask.getPriority()).isEqualTo(DEFAULT_PRIORITY);
assertThat(testTask.getUser()).isEqualTo(DEFAULT_USER);
assertThat(testTask.getExpirationDate()).isEqualTo(DEFAULT_EXPIRATION_DATE);
}
示例10: testSocialConnections
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@WithMockUser("user123")
public void testSocialConnections() throws Exception {
LinkedMultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<>();
connections.add(connection.getKey().getProviderId(), connection);
when(connectionRepository.findAllConnections()).thenReturn(connections);
MockHttpServletRequestBuilder request = get("/api/profile/socials")
.contentType(MediaType.APPLICATION_JSON);
MockHttpServletResponse response = mockMvc.perform(request)
.andDo(document("user-profile-socials-list"))
.andReturn()
.getResponse();
assertThat(response.getStatus()).isEqualTo(200);
JsonNode jsonResponse = objectMapper.readTree(response.getContentAsByteArray());
assertThat(jsonResponse.isObject()).isTrue();
assertThat(jsonResponse.has(PROVIDER_ID)).isTrue();
assertThat(jsonResponse.get(PROVIDER_ID).isObject()).isTrue();
assertThat(jsonResponse.get(PROVIDER_ID).get("imageUrl").textValue()).isEqualTo(connection.getImageUrl());
verify(connectionRepository).findAllConnections();
}
示例11: testFilter_withValidNotesGetCall_shouldReturnDecryptedNote
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@WithMockUser(username="[email protected]",authorities={"ADMIN","AUTHOR"},password="none")
public void testFilter_withValidNotesGetCall_shouldReturnDecryptedNote() throws Exception {
AuthUserResponse response = new AuthUserResponse();
response.setCryptKey("sikdfyh089oay3i3ip2wr3o2rj3wio8yf");
when(userService.getUserInfoFromAuthEmail(matches("[email protected]"))).thenReturn(response);
String decryptedSecretMessage = "{\"id\":\"no1\",\"title\":\"top secret\",\"lastEdit\":null,\"archived\":false,\"content\":\"Prosciutto brisket pork turkey filet mignon landjaeger cow.\"}";
when(encryptionService.decryptNote(any(), matches(response.getCryptKey()),any()))
.thenReturn(new ByteArrayInputStream(decryptedSecretMessage.getBytes()));
MvcResult result =
mockMvc.perform(get("/api/v1/notes/existingNoteId").contentType(jsonContentType)).andReturn();
assertEquals("correct response returns 200", 200, result.getResponse().getStatus());
assertEquals("check mock-decrypted message", decryptedSecretMessage, result.getResponse().getContentAsString());
verify(encryptionService,times(1)).decryptNote(any(), matches(response.getCryptKey()),any());
}
示例12: deleteTask
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@Transactional
@WithMockUser(username="[email protected]",authorities={"ROLE_ADMIN"}, password = "admin")
public void deleteTask() throws Exception {
// Initialize the database
taskRepository.saveAndFlush(task);
int databaseSizeBeforeDelete = taskRepository.findAll().size();
// Get the task
restTaskMockMvc.perform(delete("/api/tasks/{id}", task.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Task> taskList = taskRepository.findAll();
assertThat(taskList).hasSize(databaseSizeBeforeDelete - 1);
}
示例13: testUpdateProfile
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@WithMockUser("user123")
public void testUpdateProfile() throws Exception {
final UserEntity user = new UserEntity()
.setId("user125")
.setUsername("user")
.setEmail("[email protected]");
when(profileService.updateProfile(eq("user123"), any())).thenReturn(user);
MockHttpServletRequestBuilder request = put("/api/profile")
.content("{\"username\": \"user1234\"}")
.contentType(MediaType.APPLICATION_JSON);
MockHttpServletResponse response = mockMvc.perform(request)
.andDo(document("user-profile-update"))
.andReturn()
.getResponse();
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getContentAsByteArray())
.isEqualTo(objectMapper.writeValueAsBytes(ProfileRestData.builder().fromUserEntity(user).build()));
verify(profileService).updateProfile(eq("user123"), any());
}
示例14: testUpdateProfilePassword
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@WithMockUser("user123")
public void testUpdateProfilePassword() throws Exception {
final UserEntity user = new UserEntity()
.setId("user123")
.setUsername("user")
.setEmail("[email protected]");
when(profileService.updateProfilePassword(eq("user123"), any())).thenReturn(user);
MockHttpServletRequestBuilder request = put("/api/profile/password")
.content("{\"username\": \"user123\"}")
.contentType(MediaType.APPLICATION_JSON);
MockHttpServletResponse response = mockMvc.perform(request)
.andDo(document("user-profile-password-update"))
.andReturn()
.getResponse();
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getContentAsByteArray())
.isEqualTo(objectMapper.writeValueAsBytes(ProfileRestData.builder().fromUserEntity(user).build()));
verify(profileService).updateProfilePassword(eq("user123"), any());
}
示例15: whenRefreshTokenCalledWithAdminRoleThenExpectSuccessResponse
import org.springframework.security.test.context.support.WithMockUser; //导入依赖的package包/类
@Test
@WithMockUser(roles = "ADMIN")
public void whenRefreshTokenCalledWithAdminRoleThenExpectSuccessResponse() throws Exception {
final Role authority = new Role();
authority.setId(1L);
authority.setName(RoleName.ROLE_ADMIN);
final List<Role> authorities = Collections.singletonList(authority);
final User user = new User();
user.setUsername("admin");
user.setRoles(authorities);
user.setEnabled(true);
user.setLastPasswordResetDate(new Date(System.currentTimeMillis() + 1000 * 1000));
final JwtUser jwtUser = JwtUserFactory.create(user);
when(jwtUtils.getUsernameFromTokenClaims(any())).thenReturn(user.getUsername());
when(userDetailsService.loadUserByUsername(eq(user.getUsername()))).thenReturn(jwtUser);
when(jwtUtils.canTokenBeRefreshed(any(), any())).thenReturn(true);
mockMvc.perform(get("/refresh")).andExpect(status().is2xxSuccessful());
}