當前位置: 首頁>>代碼示例>>Java>>正文


Java WithMockUser類代碼示例

本文整理匯總了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());
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:26,代碼來源:OAuth2ClientRestControllerTest.java

示例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);
}
 
開發者ID:asanzdiego,項目名稱:codemotion-2017-taller-de-jhipster,代碼行數:19,代碼來源:TaskResourceIntTest.java

示例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());
}
 
開發者ID:asanzdiego,項目名稱:codemotion-2017-taller-de-jhipster,代碼行數:17,代碼來源:AccountResourceIntTest.java

示例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());
}
 
開發者ID:oktadeveloper,項目名稱:jhipster-microservices-example,代碼行數:17,代碼來源:AccountResourceIntTest.java

示例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();
}
 
開發者ID:pascalgrimaud,項目名稱:qualitoast,代碼行數:17,代碼來源:AccountResourceIntTest.java

示例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());
}
 
開發者ID:deepu105,項目名稱:spring-io,代碼行數:17,代碼來源:AccountResourceIntTest.java

示例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());
}
 
開發者ID:daflockinger,項目名稱:poppynotes,代碼行數:20,代碼來源:InCommingNoteEncryptingFilterTest.java

示例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);
}
 
開發者ID:asanzdiego,項目名稱:codemotion-2017-taller-de-jhipster,代碼行數:22,代碼來源:TaskResourceIntTest.java

示例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();
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:21,代碼來源:ProfileSocialRestControllerTest.java

示例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());
}
 
開發者ID:daflockinger,項目名稱:poppynotes,代碼行數:18,代碼來源:OutGoingNoteDecryptingFilterTest.java

示例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);
}
 
開發者ID:asanzdiego,項目名稱:codemotion-2017-taller-de-jhipster,代碼行數:18,代碼來源:TaskResourceIntTest.java

示例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());
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:21,代碼來源:ProfileRestControllerTest.java

示例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());
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:21,代碼來源:ProfileRestControllerTest.java

示例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());
}
 
開發者ID:gazbert,項目名稱:bxbot-ui-server,代碼行數:24,代碼來源:TestAuthenticationController.java


注:本文中的org.springframework.security.test.context.support.WithMockUser類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。