模拟Spring Security上下文进行单元测试

今天,在为一种Java方法编写单元测试用例时,如下所示:

public ApplicationUser getApplicationUser() {
	ApplicationUser applicationUser = (ApplicationUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	return applicationUser;
}

我想模拟Spring Security Context以获取Principal,以实现与我模拟方法的每个级别相同的目标,如下所示:

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import com.arpit.security.user.ApplicationUser;

public class BaseTest {

	@Before
	public void setupMock() {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void mockApplicationUser() {
		ApplicationUser applicationUser = mock(ApplicationUser.class);
		Authentication authentication = mock(Authentication.class);
		SecurityContext securityContext = mock(SecurityContext.class);
		when(securityContext.getAuthentication()).thenReturn(authentication);
		SecurityContextHolder.setContext(securityContext);
		when(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).thenReturn(applicationUser);
	}

}

翻译自: https://www.javacodegeeks.com/2017/05/mocking-spring-security-context-unit-testing.html

你可能感兴趣的:(模拟Spring Security上下文进行单元测试)