Remove Powermock

Powermock does not support JUnit5 yet, so we need to remove it
to support JUnit 5. Additionally, maintaining additional libraries
adds extra work for the team.

Mockito now supports final classes and static method mocking. This
commit replaces Powermock with mockito-inline.

Closes gh-6025
This commit is contained in:
Rob Winch 2021-07-07 09:11:53 -05:00
parent e30b45c6fb
commit 14240b2559
43 changed files with 300 additions and 286 deletions

View File

@ -27,7 +27,6 @@ import org.gradle.api.plugins.JavaPlugin
* <li>sockDependencies</li> * <li>sockDependencies</li>
* <li>seleniumDependencies</li> * <li>seleniumDependencies</li>
* <li>gebDependencies</li> * <li>gebDependencies</li>
* <li>powerMockDependencies</li>
* <li>slf4jDependencies</li> * <li>slf4jDependencies</li>
* <li>jstlDependencies</li> * <li>jstlDependencies</li>
* <li>apachedsDependencies</li> * <li>apachedsDependencies</li>
@ -61,28 +60,6 @@ public class DependencySetPlugin implements Plugin<Project> {
"org.codehaus.groovy:groovy-all" "org.codehaus.groovy:groovy-all"
] ]
project.ext.powerMockDependencies = [
"org.powermock:powermock-core",
"org.powermock:powermock-api-support",
"org.powermock:powermock-module-junit4-common",
"org.powermock:powermock-module-junit4",
project.dependencies.create("org.powermock:powermock-api-mockito") {
exclude group: 'org.mockito', module: 'mockito-all'
},
"org.powermock:powermock-reflect"
]
project.ext.powerMock2Dependencies = [
"org.powermock:powermock-core",
"org.powermock:powermock-api-support",
"org.powermock:powermock-module-junit4-common",
"org.powermock:powermock-module-junit4",
project.dependencies.create("org.powermock:powermock-api-mockito2") {
exclude group: 'org.mockito', module: 'mockito-all'
},
"org.powermock:powermock-reflect"
]
project.ext.slf4jDependencies = [ project.ext.slf4jDependencies = [
"org.slf4j:slf4j-api", "org.slf4j:slf4j-api",
"org.slf4j:jcl-over-slf4j", "org.slf4j:jcl-over-slf4j",

View File

@ -12,10 +12,9 @@ repositories {
dependencies { dependencies {
testCompile spockDependencies testCompile spockDependencies
testCompile gebDependencies testCompile gebDependencies
testCompile powerMockDependencies
testCompile seleniumDependencies testCompile seleniumDependencies
testCompile slf4jDependencies testCompile slf4jDependencies
testCompile springCoreDependency testCompile springCoreDependency
testCompile jstlDependencies testCompile jstlDependencies
testCompile apachedsDependencies testCompile apachedsDependencies
} }

View File

@ -704,13 +704,7 @@ def deps = [
"xml-apis:xml-apis" : "1.4.01", "xml-apis:xml-apis" : "1.4.01",
"xmlunit:xmlunit" : "1.6", "xmlunit:xmlunit" : "1.6",
"xom:xom" : "1.2.5", "xom:xom" : "1.2.5",
"org.gebish:geb-spock" : "1.1.1", "org.gebish:geb-spock" : "1.1.1"
"org.powermock:powermock-core" : "1.6.2",
"org.powermock:powermock-api-support" : "1.6.2",
"org.powermock:powermock-module-junit4-common" : "1.6.2",
"org.powermock:powermock-module-junit4" : "1.6.2",
"org.powermock:powermock-api-mockito" : "1.6.2",
"org.powermock:powermock-reflect" : "1.6.2"
] ]
configurations.all { configurations.all {
@ -721,4 +715,4 @@ configurations.all {
details.useVersion deps[id] details.useVersion deps[id]
} }
} }
} }

View File

@ -52,7 +52,6 @@ dependencies {
testImplementation project(path: ':spring-security-saml2-service-provider', configuration: 'opensaml4MainCompile') testImplementation project(path: ':spring-security-saml2-service-provider', configuration: 'opensaml4MainCompile')
testImplementation project(path : ':spring-security-web', configuration : 'tests') testImplementation project(path : ':spring-security-web', configuration : 'tests')
testImplementation apachedsDependencies testImplementation apachedsDependencies
testImplementation powerMock2Dependencies
testImplementation 'com.squareup.okhttp3:mockwebserver' testImplementation 'com.squareup.okhttp3:mockwebserver'
testImplementation 'ch.qos.logback:logback-classic' testImplementation 'ch.qos.logback:logback-classic'
testImplementation 'io.projectreactor.netty:reactor-netty' testImplementation 'io.projectreactor.netty:reactor-netty'
@ -66,6 +65,8 @@ dependencies {
testImplementation 'org.eclipse.persistence:javax.persistence' testImplementation 'org.eclipse.persistence:javax.persistence'
testImplementation 'org.hibernate:hibernate-entitymanager' testImplementation 'org.hibernate:hibernate-entitymanager'
testImplementation 'org.hsqldb:hsqldb' testImplementation 'org.hsqldb:hsqldb'
testImplementation 'org.mockito:mockito-core'
testImplementation "org.mockito:mockito-inline"
testImplementation ('org.openid4java:openid4java-nodeps') { testImplementation ('org.openid4java:openid4java-nodeps') {
exclude group: 'com.google.code.guice', module: 'guice' exclude group: 'com.google.code.guice', module: 'guice'
} }

View File

@ -19,13 +19,12 @@ package org.springframework.security.config;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito; import org.mockito.Answers;
import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.mockito.MockedStatic;
import org.powermock.modules.junit4.PowerMockRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.messaging.Message;
import org.springframework.security.config.util.InMemoryXmlApplicationContext; import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
@ -41,9 +40,7 @@ import static org.mockito.Mockito.verifyZeroInteractions;
* @author Rob Winch * @author Rob Winch
* @since 3.0 * @since 3.0
*/ */
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareForTest({ ClassUtils.class })
@PowerMockIgnore({ "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*", "javax.xml.parsers.*" })
public class SecurityNamespaceHandlerTests { public class SecurityNamespaceHandlerTests {
// @formatter:off // @formatter:off
@ -60,6 +57,9 @@ public class SecurityNamespaceHandlerTests {
private static final String FILTER_CHAIN_PROXY_CLASSNAME = "org.springframework.security.web.FilterChainProxy"; private static final String FILTER_CHAIN_PROXY_CLASSNAME = "org.springframework.security.web.FilterChainProxy";
@Mock(answer = Answers.CALLS_REAL_METHODS)
private MockedStatic<ClassUtils> classUtils;
@Test @Test
public void constructionSucceeds() { public void constructionSucceeds() {
new SecurityNamespaceHandler(); new SecurityNamespaceHandler();
@ -83,24 +83,18 @@ public class SecurityNamespaceHandlerTests {
@Test @Test
public void initDoesNotLogErrorWhenFilterChainProxyFailsToLoad() throws Exception { public void initDoesNotLogErrorWhenFilterChainProxyFailsToLoad() throws Exception {
String className = "javax.servlet.Filter"; String className = "javax.servlet.Filter";
PowerMockito.spy(ClassUtils.class);
PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
Log logger = mock(Log.class); Log logger = mock(Log.class);
SecurityNamespaceHandler handler = new SecurityNamespaceHandler(); SecurityNamespaceHandler handler = new SecurityNamespaceHandler();
ReflectionTestUtils.setField(handler, "logger", logger); ReflectionTestUtils.setField(handler, "logger", logger);
expectClassUtilsForNameThrowsNoClassDefFoundError(className);
handler.init(); handler.init();
PowerMockito.verifyStatic(ClassUtils.class);
ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
verifyZeroInteractions(logger); verifyZeroInteractions(logger);
} }
@Test @Test
public void filterNoClassDefFoundError() throws Exception { public void filterNoClassDefFoundError() throws Exception {
String className = "javax.servlet.Filter"; String className = "javax.servlet.Filter";
PowerMockito.spy(ClassUtils.class); expectClassUtilsForNameThrowsNoClassDefFoundError(className);
PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
assertThatExceptionOfType(BeanDefinitionParsingException.class) assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK)) .isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
.withMessageContaining("NoClassDefFoundError: " + className); .withMessageContaining("NoClassDefFoundError: " + className);
@ -109,9 +103,7 @@ public class SecurityNamespaceHandlerTests {
@Test @Test
public void filterNoClassDefFoundErrorNoHttpBlock() throws Exception { public void filterNoClassDefFoundErrorNoHttpBlock() throws Exception {
String className = "javax.servlet.Filter"; String className = "javax.servlet.Filter";
PowerMockito.spy(ClassUtils.class); expectClassUtilsForNameThrowsNoClassDefFoundError(className);
PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER);
// should load just fine since no http block // should load just fine since no http block
} }
@ -119,9 +111,7 @@ public class SecurityNamespaceHandlerTests {
@Test @Test
public void filterChainProxyClassNotFoundException() throws Exception { public void filterChainProxyClassNotFoundException() throws Exception {
String className = FILTER_CHAIN_PROXY_CLASSNAME; String className = FILTER_CHAIN_PROXY_CLASSNAME;
PowerMockito.spy(ClassUtils.class); expectClassUtilsForNameThrowsClassNotFoundException(className);
PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
assertThatExceptionOfType(BeanDefinitionParsingException.class) assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK)) .isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
.withMessageContaining("ClassNotFoundException: " + className); .withMessageContaining("ClassNotFoundException: " + className);
@ -130,9 +120,7 @@ public class SecurityNamespaceHandlerTests {
@Test @Test
public void filterChainProxyClassNotFoundExceptionNoHttpBlock() throws Exception { public void filterChainProxyClassNotFoundExceptionNoHttpBlock() throws Exception {
String className = FILTER_CHAIN_PROXY_CLASSNAME; String className = FILTER_CHAIN_PROXY_CLASSNAME;
PowerMockito.spy(ClassUtils.class); expectClassUtilsForNameThrowsClassNotFoundException(className);
PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER);
// should load just fine since no http block // should load just fine since no http block
} }
@ -140,11 +128,19 @@ public class SecurityNamespaceHandlerTests {
@Test @Test
public void websocketNotFoundExceptionNoMessageBlock() throws Exception { public void websocketNotFoundExceptionNoMessageBlock() throws Exception {
String className = FILTER_CHAIN_PROXY_CLASSNAME; String className = FILTER_CHAIN_PROXY_CLASSNAME;
PowerMockito.spy(ClassUtils.class); expectClassUtilsForNameThrowsClassNotFoundException(className);
PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
eq(Message.class.getName()), any(ClassLoader.class));
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER);
// should load just fine since no websocket block // should load just fine since no websocket block
} }
private void expectClassUtilsForNameThrowsNoClassDefFoundError(String className) {
this.classUtils.when(() -> ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any()))
.thenThrow(new NoClassDefFoundError(className));
}
private void expectClassUtilsForNameThrowsClassNotFoundException(String className) {
this.classUtils.when(() -> ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any()))
.thenThrow(new ClassNotFoundException(className));
}
} }

View File

@ -23,10 +23,9 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.powermock.api.mockito.PowerMockito; import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.mockito.MockedStatic;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.io.support.SpringFactoriesLoader;
@ -56,11 +55,8 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
* @author Rob Winch * @author Rob Winch
* *
*/ */
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareForTest({ SpringFactoriesLoader.class, WebAsyncManager.class }) public class WebSecurityConfigurerAdapterMockitoTests {
@PowerMockIgnore({ "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*", "javax.xml.parsers.*",
"javax.xml.transform.*" })
public class WebSecurityConfigurerAdapterPowermockTests {
ConfigurableWebApplicationContext context; ConfigurableWebApplicationContext context;
@ -70,6 +66,9 @@ public class WebSecurityConfigurerAdapterPowermockTests {
@Autowired @Autowired
private MockMvc mockMvc; private MockMvc mockMvc;
@Mock
private MockedStatic<SpringFactoriesLoader> springFactoriesLoader;
@After @After
public void close() { public void close() {
if (this.context != null) { if (this.context != null) {
@ -79,11 +78,10 @@ public class WebSecurityConfigurerAdapterPowermockTests {
@Test @Test
public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() { public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() {
PowerMockito.spy(SpringFactoriesLoader.class);
DefaultConfigurer configurer = new DefaultConfigurer(); DefaultConfigurer configurer = new DefaultConfigurer();
PowerMockito this.springFactoriesLoader.when(
.when(SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader())) () -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
.thenReturn(Arrays.<AbstractHttpConfigurer>asList(configurer)); .thenReturn(Arrays.asList(configurer));
loadConfig(Config.class); loadConfig(Config.class);
assertThat(configurer.init).isTrue(); assertThat(configurer.init).isTrue();
assertThat(configurer.configure).isTrue(); assertThat(configurer.configure).isTrue();

View File

@ -16,17 +16,11 @@
package org.springframework.security.config.annotation.web.configurers; package org.springframework.security.config.annotation.web.configurers;
import java.lang.reflect.Method;
import javax.servlet.Filter; import javax.servlet.Filter;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@ -50,13 +44,8 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Rob Winch * @author Rob Winch
*/ */
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({ "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*", "javax.xml.parsers.*" })
public class SessionManagementConfigurerServlet31Tests { public class SessionManagementConfigurerServlet31Tests {
@Mock
Method method;
MockHttpServletRequest request; MockHttpServletRequest request;
MockHttpServletResponse response; MockHttpServletResponse response;

View File

@ -16,18 +16,11 @@
package org.springframework.security.config.http; package org.springframework.security.config.http;
import java.lang.reflect.Method;
import javax.servlet.Filter; import javax.servlet.Filter;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockFilterChain;
@ -38,7 +31,6 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.context.HttpRequestResponseHolder; import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -46,9 +38,6 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Rob Winch * @author Rob Winch
* *
*/ */
@RunWith(PowerMockRunner.class)
@PrepareForTest({ ReflectionUtils.class, Method.class })
@PowerMockIgnore({ "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*", "javax.xml.parsers.*" })
public class SessionManagementConfigServlet31Tests { public class SessionManagementConfigServlet31Tests {
// @formatter:off // @formatter:off
@ -61,9 +50,6 @@ public class SessionManagementConfigServlet31Tests {
+ "</authentication-manager>"; + "</authentication-manager>";
// @formatter:on // @formatter:on
@Mock
Method method;
MockHttpServletRequest request; MockHttpServletRequest request;
MockHttpServletResponse response; MockHttpServletResponse response;

View File

@ -19,15 +19,13 @@ package org.springframework.security.config.http;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.beans.factory.xml.ParserContext; import org.springframework.beans.factory.xml.ParserContext;
import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareOnlyThisForTest(ParserContext.class)
public class WebConfigUtilsTests { public class WebConfigUtilsTests {
public static final String URL = "/url"; public static final String URL = "/url";

View File

@ -20,9 +20,10 @@ dependencies {
optional 'org.springframework:spring-tx' optional 'org.springframework:spring-tx'
optional 'org.jetbrains.kotlinx:kotlinx-coroutines-reactor' optional 'org.jetbrains.kotlinx:kotlinx-coroutines-reactor'
testImplementation powerMock2Dependencies
testImplementation 'commons-collections:commons-collections' testImplementation 'commons-collections:commons-collections'
testImplementation 'io.projectreactor:reactor-test' testImplementation 'io.projectreactor:reactor-test'
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.mockito:mockito-inline'
testImplementation 'org.skyscreamer:jsonassert' testImplementation 'org.skyscreamer:jsonassert'
testImplementation 'org.slf4j:jcl-over-slf4j' testImplementation 'org.slf4j:jcl-over-slf4j'
testImplementation 'org.springframework:spring-test' testImplementation 'org.springframework:spring-test'

View File

@ -24,9 +24,8 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito; import org.mockito.MockedStatic;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
@ -41,8 +40,7 @@ import static org.mockito.ArgumentMatchers.eq;
* @since 3.2 * @since 3.2
* *
*/ */
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareForTest({ DelegatingSecurityContextRunnable.class, DelegatingSecurityContextCallable.class })
public abstract class AbstractDelegatingSecurityContextTestSupport { public abstract class AbstractDelegatingSecurityContextTestSupport {
@Mock @Mock
@ -66,22 +64,26 @@ public abstract class AbstractDelegatingSecurityContextTestSupport {
@Mock @Mock
protected Runnable wrappedRunnable; protected Runnable wrappedRunnable;
public final void explicitSecurityContextPowermockSetup() throws Exception { @Mock
PowerMockito.spy(DelegatingSecurityContextCallable.class); protected MockedStatic<DelegatingSecurityContextCallable> delegatingSecurityContextCallable;
PowerMockito.doReturn(this.wrappedCallable).when(DelegatingSecurityContextCallable.class, "create",
eq(this.callable), this.securityContextCaptor.capture()); @Mock
PowerMockito.spy(DelegatingSecurityContextRunnable.class); protected MockedStatic<DelegatingSecurityContextRunnable> delegatingSecurityContextRunnable;
PowerMockito.doReturn(this.wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create",
eq(this.runnable), this.securityContextCaptor.capture()); public final void explicitSecurityContextSetup() throws Exception {
this.delegatingSecurityContextCallable.when(
() -> DelegatingSecurityContextCallable.create(eq(this.callable), this.securityContextCaptor.capture()))
.thenReturn(this.wrappedCallable);
this.delegatingSecurityContextRunnable.when(
() -> DelegatingSecurityContextRunnable.create(eq(this.runnable), this.securityContextCaptor.capture()))
.thenReturn(this.wrappedRunnable);
} }
public final void currentSecurityContextPowermockSetup() throws Exception { public final void currentSecurityContextSetup() throws Exception {
PowerMockito.spy(DelegatingSecurityContextCallable.class); this.delegatingSecurityContextCallable.when(() -> DelegatingSecurityContextCallable.create(this.callable, null))
PowerMockito.doReturn(this.wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", .thenReturn(this.wrappedCallable);
this.callable, null); this.delegatingSecurityContextRunnable.when(() -> DelegatingSecurityContextRunnable.create(this.runnable, null))
PowerMockito.spy(DelegatingSecurityContextRunnable.class); .thenReturn(this.wrappedRunnable);
PowerMockito.doReturn(this.wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create",
this.runnable, null);
} }
@Before @Before

View File

@ -33,7 +33,7 @@ public class CurrentDelegatingSecurityContextExecutorServiceTests
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
super.currentSecurityContextPowermockSetup(); super.currentSecurityContextSetup();
} }
@Override @Override

View File

@ -32,7 +32,7 @@ public class CurrentDelegatingSecurityContextExecutorTests extends AbstractDeleg
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
super.currentSecurityContextPowermockSetup(); super.currentSecurityContextSetup();
} }
@Override @Override

View File

@ -33,7 +33,7 @@ public class CurrentDelegatingSecurityContextScheduledExecutorServiceTests
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
this.currentSecurityContextPowermockSetup(); this.currentSecurityContextSetup();
} }
@Override @Override

View File

@ -33,7 +33,7 @@ public class DelegatingSecurityContextSupportTests extends AbstractDelegatingSec
@Test @Test
public void wrapCallable() throws Exception { public void wrapCallable() throws Exception {
explicitSecurityContextPowermockSetup(); explicitSecurityContextSetup();
this.support = new ConcreteDelegatingSecurityContextSupport(this.securityContext); this.support = new ConcreteDelegatingSecurityContextSupport(this.securityContext);
assertThat(this.support.wrap(this.callable)).isSameAs(this.wrappedCallable); assertThat(this.support.wrap(this.callable)).isSameAs(this.wrappedCallable);
assertThat(this.securityContextCaptor.getValue()).isSameAs(this.securityContext); assertThat(this.securityContextCaptor.getValue()).isSameAs(this.securityContext);
@ -41,14 +41,14 @@ public class DelegatingSecurityContextSupportTests extends AbstractDelegatingSec
@Test @Test
public void wrapCallableNullSecurityContext() throws Exception { public void wrapCallableNullSecurityContext() throws Exception {
currentSecurityContextPowermockSetup(); currentSecurityContextSetup();
this.support = new ConcreteDelegatingSecurityContextSupport(null); this.support = new ConcreteDelegatingSecurityContextSupport(null);
assertThat(this.support.wrap(this.callable)).isSameAs(this.wrappedCallable); assertThat(this.support.wrap(this.callable)).isSameAs(this.wrappedCallable);
} }
@Test @Test
public void wrapRunnable() throws Exception { public void wrapRunnable() throws Exception {
explicitSecurityContextPowermockSetup(); explicitSecurityContextSetup();
this.support = new ConcreteDelegatingSecurityContextSupport(this.securityContext); this.support = new ConcreteDelegatingSecurityContextSupport(this.securityContext);
assertThat(this.support.wrap(this.runnable)).isSameAs(this.wrappedRunnable); assertThat(this.support.wrap(this.runnable)).isSameAs(this.wrappedRunnable);
assertThat(this.securityContextCaptor.getValue()).isSameAs(this.securityContext); assertThat(this.securityContextCaptor.getValue()).isSameAs(this.securityContext);
@ -56,7 +56,7 @@ public class DelegatingSecurityContextSupportTests extends AbstractDelegatingSec
@Test @Test
public void wrapRunnableNullSecurityContext() throws Exception { public void wrapRunnableNullSecurityContext() throws Exception {
currentSecurityContextPowermockSetup(); currentSecurityContextSetup();
this.support = new ConcreteDelegatingSecurityContextSupport(null); this.support = new ConcreteDelegatingSecurityContextSupport(null);
assertThat(this.support.wrap(this.runnable)).isSameAs(this.wrappedRunnable); assertThat(this.support.wrap(this.runnable)).isSameAs(this.wrappedRunnable);
} }

View File

@ -33,7 +33,7 @@ public class ExplicitDelegatingSecurityContextExecutorServiceTests
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
super.explicitSecurityContextPowermockSetup(); super.explicitSecurityContextSetup();
} }
@Override @Override

View File

@ -32,7 +32,7 @@ public class ExplicitDelegatingSecurityContextExecutorTests extends AbstractDele
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
super.explicitSecurityContextPowermockSetup(); super.explicitSecurityContextSetup();
} }
@Override @Override

View File

@ -33,7 +33,7 @@ public class ExplicitDelegatingSecurityContextScheduledExecutorServiceTests
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
this.explicitSecurityContextPowermockSetup(); this.explicitSecurityContextSetup();
} }
@Override @Override

View File

@ -16,18 +16,22 @@
package org.springframework.security.core; package org.springframework.security.core;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito; import org.mockito.MockedStatic;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import org.springframework.core.SpringVersion; import org.springframework.core.SpringVersion;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -42,21 +46,29 @@ import static org.mockito.Mockito.verifyZeroInteractions;
* @author Luke Taylor * @author Luke Taylor
* @author Rob Winch * @author Rob Winch
*/ */
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareForTest({ SpringSecurityCoreVersion.class, SpringVersion.class })
public class SpringSecurityCoreVersionTests { public class SpringSecurityCoreVersionTests {
@Mock @Mock
private Log logger; private Log logger;
@Mock(answer = Answers.CALLS_REAL_METHODS)
private MockedStatic<SpringVersion> springVersion;
@Mock(answer = Answers.CALLS_REAL_METHODS)
private MockedStatic<SpringSecurityCoreVersion> springSecurityCoreVersion;
@Before @Before
public void setup() { public void setup() throws Exception {
Whitebox.setInternalState(SpringSecurityCoreVersion.class, this.logger); Field logger = ReflectionUtils.findField(SpringSecurityCoreVersion.class, "logger");
StaticFinalReflectionUtils.setField(logger, this.logger);
} }
@After @After
public void cleanup() throws Exception { public void cleanup() throws Exception {
System.clearProperty(getDisableChecksProperty()); System.clearProperty(getDisableChecksProperty());
Field logger = ReflectionUtils.findField(SpringSecurityCoreVersion.class, "logger");
StaticFinalReflectionUtils.setField(logger, LogFactory.getLog(SpringSecurityCoreVersion.class));
} }
@Test @Test
@ -79,40 +91,34 @@ public class SpringSecurityCoreVersionTests {
@Test @Test
public void noLoggingIfVersionsAreEqual() throws Exception { public void noLoggingIfVersionsAreEqual() throws Exception {
String version = "1"; String version = "1";
PowerMockito.spy(SpringSecurityCoreVersion.class); expectSpringSecurityVersionThenReturn(version);
PowerMockito.spy(SpringVersion.class); expectSpringVersionThenReturn(version);
PowerMockito.doReturn(version).when(SpringSecurityCoreVersion.class, "getVersion");
PowerMockito.doReturn(version).when(SpringVersion.class, "getVersion");
performChecks(); performChecks();
verifyZeroInteractions(this.logger); verifyZeroInteractions(this.logger);
} }
@Test @Test
public void noLoggingIfSpringVersionNull() throws Exception { public void noLoggingIfSpringVersionNull() throws Exception {
PowerMockito.spy(SpringSecurityCoreVersion.class); String version = "1";
PowerMockito.spy(SpringVersion.class); expectSpringSecurityVersionThenReturn(version);
PowerMockito.doReturn("1").when(SpringSecurityCoreVersion.class, "getVersion"); expectSpringVersionThenReturn(null);
PowerMockito.doReturn(null).when(SpringVersion.class, "getVersion");
performChecks(); performChecks();
verifyZeroInteractions(this.logger); verifyZeroInteractions(this.logger);
} }
@Test @Test
public void warnIfSpringVersionTooSmall() throws Exception { public void warnIfSpringVersionTooSmall() throws Exception {
PowerMockito.spy(SpringSecurityCoreVersion.class); expectSpringSecurityVersionThenReturn("3");
PowerMockito.spy(SpringVersion.class); expectSpringVersionThenReturn("2");
PowerMockito.doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion");
PowerMockito.doReturn("2").when(SpringVersion.class, "getVersion");
performChecks(); performChecks();
verify(this.logger, times(1)).warn(any()); verify(this.logger, times(1)).warn(any());
} }
@Test @Test
public void noWarnIfSpringVersionLarger() throws Exception { public void noWarnIfSpringVersionLarger() throws Exception {
PowerMockito.spy(SpringSecurityCoreVersion.class); String version = "4.0.0.RELEASE";
PowerMockito.spy(SpringVersion.class); expectSpringSecurityVersionThenReturn(version);
PowerMockito.doReturn("4.0.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion"); expectSpringVersionThenReturn(version);
PowerMockito.doReturn("4.0.0.RELEASE").when(SpringVersion.class, "getVersion");
performChecks(); performChecks();
verify(this.logger, never()).warn(any()); verify(this.logger, never()).warn(any());
} }
@ -121,20 +127,16 @@ public class SpringSecurityCoreVersionTests {
@Test @Test
public void noWarnIfSpringPatchVersionDoubleDigits() throws Exception { public void noWarnIfSpringPatchVersionDoubleDigits() throws Exception {
String minSpringVersion = "3.2.8.RELEASE"; String minSpringVersion = "3.2.8.RELEASE";
PowerMockito.spy(SpringSecurityCoreVersion.class); expectSpringSecurityVersionThenReturn("3.2.0.RELEASE");
PowerMockito.spy(SpringVersion.class); expectSpringVersionThenReturn("3.2.10.RELEASE");
PowerMockito.doReturn("3.2.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion");
PowerMockito.doReturn("3.2.10.RELEASE").when(SpringVersion.class, "getVersion");
performChecks(minSpringVersion); performChecks(minSpringVersion);
verify(this.logger, never()).warn(any()); verify(this.logger, never()).warn(any());
} }
@Test @Test
public void noLoggingIfPropertySet() throws Exception { public void noLoggingIfPropertySet() throws Exception {
PowerMockito.spy(SpringSecurityCoreVersion.class); expectSpringSecurityVersionThenReturn("3");
PowerMockito.spy(SpringVersion.class); expectSpringVersionThenReturn("2");
PowerMockito.doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion");
PowerMockito.doReturn("2").when(SpringVersion.class, "getVersion");
System.setProperty(getDisableChecksProperty(), Boolean.TRUE.toString()); System.setProperty(getDisableChecksProperty(), Boolean.TRUE.toString());
performChecks(); performChecks();
verifyZeroInteractions(this.logger); verifyZeroInteractions(this.logger);
@ -144,12 +146,25 @@ public class SpringSecurityCoreVersionTests {
return SpringSecurityCoreVersion.class.getName().concat(".DISABLE_CHECKS"); return SpringSecurityCoreVersion.class.getName().concat(".DISABLE_CHECKS");
} }
private void performChecks() throws Exception { private void performChecks() {
Whitebox.invokeMethod(SpringSecurityCoreVersion.class, "performVersionChecks"); Method method = ReflectionUtils.findMethod(SpringSecurityCoreVersion.class, "performVersionChecks");
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, null);
} }
private void performChecks(String minSpringVersion) throws Exception { private void performChecks(String minSpringVersion) {
Whitebox.invokeMethod(SpringSecurityCoreVersion.class, "performVersionChecks", minSpringVersion); Method method = ReflectionUtils.findMethod(SpringSecurityCoreVersion.class, "performVersionChecks",
String.class);
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, null, minSpringVersion);
}
private void expectSpringSecurityVersionThenReturn(String version) {
this.springSecurityCoreVersion.when(SpringSecurityCoreVersion::getVersion).thenReturn(version);
}
private void expectSpringVersionThenReturn(String version) {
this.springVersion.when(SpringVersion::getVersion).thenReturn(version);
} }
} }

View File

@ -0,0 +1,115 @@
/*
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.core;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.misc.Unsafe;
import org.springframework.objenesis.instantiator.util.UnsafeUtils;
/**
* Used for setting static variables even if they are private static final.
*
* The code in this class has been adopted from Powermock's <a href=
* "https://github.com/noushadali/powermock/blob/powermock-1.5.4/reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L326">WhiteboxImpl</a>.
*
* @author Rob Winch
*/
final class StaticFinalReflectionUtils {
/**
* Used to support setting static fields that are final using Java's Unsafe. If the
* field is not static final, use
* {@link org.springframework.test.util.ReflectionTestUtils}.
* @param field the field to set
* @param newValue the new value
*/
static void setField(final Field field, final Object newValue) {
try {
field.setAccessible(true);
int fieldModifiersMask = field.getModifiers();
boolean isFinalModifierPresent = (fieldModifiersMask & Modifier.FINAL) == Modifier.FINAL;
if (isFinalModifierPresent) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
Unsafe unsafe = UnsafeUtils.getUnsafe();
long offset = unsafe.staticFieldOffset(field);
Object base = unsafe.staticFieldBase(field);
setFieldUsingUnsafe(base, field.getType(), offset, newValue, unsafe);
return null;
}
catch (Throwable thrown) {
throw new RuntimeException(thrown);
}
}
});
}
else {
field.set(null, newValue);
}
}
catch (SecurityException ex) {
throw new RuntimeException(ex);
}
catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
}
private static void setFieldUsingUnsafe(Object base, Class type, long offset, Object newValue, Unsafe unsafe) {
if (type == Integer.TYPE) {
unsafe.putInt(base, offset, ((Integer) newValue));
}
else if (type == Short.TYPE) {
unsafe.putShort(base, offset, ((Short) newValue));
}
else if (type == Long.TYPE) {
unsafe.putLong(base, offset, ((Long) newValue));
}
else if (type == Byte.TYPE) {
unsafe.putByte(base, offset, ((Byte) newValue));
}
else if (type == Boolean.TYPE) {
unsafe.putBoolean(base, offset, ((Boolean) newValue));
}
else if (type == Float.TYPE) {
unsafe.putFloat(base, offset, ((Float) newValue));
}
else if (type == Double.TYPE) {
unsafe.putDouble(base, offset, ((Double) newValue));
}
else if (type == Character.TYPE) {
unsafe.putChar(base, offset, ((Character) newValue));
}
else {
unsafe.putObject(base, offset, newValue);
}
}
private StaticFinalReflectionUtils() {
}
}

View File

@ -33,7 +33,7 @@ public class CurrentSecurityContextSchedulingTaskExecutorTests
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
currentSecurityContextPowermockSetup(); currentSecurityContextSetup();
} }
@Override @Override

View File

@ -33,7 +33,7 @@ public class ExplicitSecurityContextSchedulingTaskExecutorTests
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
explicitSecurityContextPowermockSetup(); explicitSecurityContextSetup();
} }
@Override @Override

View File

@ -33,7 +33,7 @@ public class CurrentDelegatingSecurityContextAsyncTaskExecutorTests
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
currentSecurityContextPowermockSetup(); currentSecurityContextSetup();
} }
@Override @Override

View File

@ -41,7 +41,7 @@ public class CurrentDelegatingSecurityContextTaskExecutorTests extends AbstractD
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
currentSecurityContextPowermockSetup(); currentSecurityContextSetup();
} }
@Override @Override

View File

@ -33,7 +33,7 @@ public class ExplicitDelegatingSecurityContextAsyncTaskExecutorTests
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
explicitSecurityContextPowermockSetup(); explicitSecurityContextSetup();
} }
@Override @Override

View File

@ -41,7 +41,7 @@ public class ExplicitDelegatingSecurityContextTaskExecutorTests extends Abstract
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
explicitSecurityContextPowermockSetup(); explicitSecurityContextSetup();
} }
@Override @Override

View File

@ -56,16 +56,11 @@ dependencies {
api "org.hsqldb:hsqldb:2.6.0" api "org.hsqldb:hsqldb:2.6.0"
api "org.jasig.cas.client:cas-client-core:3.6.2" api "org.jasig.cas.client:cas-client-core:3.6.2"
api "org.mockito:mockito-core:3.9.0" api "org.mockito:mockito-core:3.9.0"
api "org.mockito:mockito-inline:3.9.0"
api "org.openid4java:openid4java-nodeps:0.9.6" api "org.openid4java:openid4java-nodeps:0.9.6"
api "org.opensaml:opensaml-core:$openSamlVersion" api "org.opensaml:opensaml-core:$openSamlVersion"
api "org.opensaml:opensaml-saml-api:$openSamlVersion" api "org.opensaml:opensaml-saml-api:$openSamlVersion"
api "org.opensaml:opensaml-saml-impl:$openSamlVersion" api "org.opensaml:opensaml-saml-impl:$openSamlVersion"
api "org.powermock:powermock-api-mockito2:2.0.9"
api "org.powermock:powermock-api-support:2.0.9"
api "org.powermock:powermock-core:2.0.9"
api "org.powermock:powermock-module-junit4-common:2.0.9"
api "org.powermock:powermock-module-junit4:2.0.9"
api "org.powermock:powermock-reflect:2.0.9"
api "org.python:jython:2.5.3" api "org.python:jython:2.5.3"
api "org.seleniumhq.selenium:htmlunit-driver:2.49.1" api "org.seleniumhq.selenium:htmlunit-driver:2.49.1"
api "org.seleniumhq.selenium:selenium-java:3.141.59" api "org.seleniumhq.selenium:selenium-java:3.141.59"

View File

@ -16,7 +16,7 @@ dependencies {
testImplementation project(path: ':spring-security-core', configuration: 'tests') testImplementation project(path: ':spring-security-core', configuration: 'tests')
testImplementation 'commons-codec:commons-codec' testImplementation 'commons-codec:commons-codec'
testImplementation powerMock2Dependencies testImplementation 'org.mockito:mockito-core'
testImplementation slf4jDependencies testImplementation slf4jDependencies
testRuntimeOnly 'org.hsqldb:hsqldb' testRuntimeOnly 'org.hsqldb:hsqldb'

View File

@ -18,7 +18,6 @@ dependencies {
testImplementation project(path: ':spring-security-oauth2-core', configuration: 'tests') testImplementation project(path: ':spring-security-oauth2-core', configuration: 'tests')
testImplementation project(path: ':spring-security-oauth2-jose', configuration: 'tests') testImplementation project(path: ':spring-security-oauth2-jose', configuration: 'tests')
testImplementation powerMock2Dependencies
testImplementation 'com.squareup.okhttp3:mockwebserver' testImplementation 'com.squareup.okhttp3:mockwebserver'
testImplementation 'io.projectreactor.netty:reactor-netty' testImplementation 'io.projectreactor.netty:reactor-netty'
testImplementation 'io.projectreactor:reactor-test' testImplementation 'io.projectreactor:reactor-test'
@ -26,6 +25,7 @@ dependencies {
testImplementation 'org.skyscreamer:jsonassert' testImplementation 'org.skyscreamer:jsonassert'
testImplementation 'io.r2dbc:r2dbc-h2:0.8.4.RELEASE' testImplementation 'io.r2dbc:r2dbc-h2:0.8.4.RELEASE'
testImplementation 'io.r2dbc:r2dbc-spi-test:0.8.5.RELEASE' testImplementation 'io.r2dbc:r2dbc-spi-test:0.8.5.RELEASE'
testImplementation 'org.mockito:mockito-core'
testRuntimeOnly 'org.hsqldb:hsqldb' testRuntimeOnly 'org.hsqldb:hsqldb'

View File

@ -10,5 +10,5 @@ dependencies {
optional 'com.nimbusds:oauth2-oidc-sdk' optional 'com.nimbusds:oauth2-oidc-sdk'
optional 'org.springframework:spring-webflux' optional 'org.springframework:spring-webflux'
testImplementation powerMock2Dependencies testImplementation 'org.mockito:mockito-core'
} }

View File

@ -10,8 +10,8 @@ dependencies {
optional 'io.projectreactor:reactor-core' optional 'io.projectreactor:reactor-core'
optional 'org.springframework:spring-webflux' optional 'org.springframework:spring-webflux'
testImplementation powerMock2Dependencies
testImplementation 'com.squareup.okhttp3:mockwebserver' testImplementation 'com.squareup.okhttp3:mockwebserver'
testImplementation 'io.projectreactor.netty:reactor-netty' testImplementation 'io.projectreactor.netty:reactor-netty'
testImplementation 'com.fasterxml.jackson.core:jackson-databind' testImplementation 'com.fasterxml.jackson.core:jackson-databind'
testImplementation 'org.mockito:mockito-core'
} }

View File

@ -22,8 +22,9 @@ dependencies {
testImplementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' testImplementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310'
testImplementation 'io.projectreactor:reactor-test' testImplementation 'io.projectreactor:reactor-test'
testImplementation 'javax.xml.bind:jaxb-api' testImplementation 'javax.xml.bind:jaxb-api'
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.mockito:mockito-inline'
testImplementation 'org.skyscreamer:jsonassert' testImplementation 'org.skyscreamer:jsonassert'
testImplementation 'org.springframework:spring-webmvc' testImplementation 'org.springframework:spring-webmvc'
testImplementation 'org.springframework:spring-tx' testImplementation 'org.springframework:spring-tx'
testImplementation powerMock2Dependencies
} }

View File

@ -25,10 +25,8 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito; import org.mockito.MockedStatic;
import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
@ -43,10 +41,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
@PowerMockIgnore({ "javax.security.auth.*", "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*",
"javax.xml.parsers.*" })
public class SecurityMockMvcRequestPostProcessorsAuthenticationTests { public class SecurityMockMvcRequestPostProcessorsAuthenticationTests {
@Captor @Captor
@ -60,10 +55,14 @@ public class SecurityMockMvcRequestPostProcessorsAuthenticationTests {
@Mock @Mock
private Authentication authentication; private Authentication authentication;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
@Before @Before
public void setup() { public void setup() {
this.request = new MockHttpServletRequest(); this.request = new MockHttpServletRequest();
mockWebTestUtils(); this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
} }
@After @After
@ -80,9 +79,4 @@ public class SecurityMockMvcRequestPostProcessorsAuthenticationTests {
assertThat(context.getAuthentication()).isSameAs(this.authentication); assertThat(context.getAuthentication()).isSameAs(this.authentication);
} }
private void mockWebTestUtils() {
PowerMockito.spy(WebTestUtils.class);
PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository);
}
} }

View File

@ -25,10 +25,8 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito; import org.mockito.MockedStatic;
import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
@ -42,10 +40,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.securityContext; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.securityContext;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
@PowerMockIgnore({ "javax.security.auth.*", "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*",
"javax.xml.parsers.*" })
public class SecurityMockMvcRequestPostProcessorsSecurityContextTests { public class SecurityMockMvcRequestPostProcessorsSecurityContextTests {
@Captor @Captor
@ -59,10 +54,14 @@ public class SecurityMockMvcRequestPostProcessorsSecurityContextTests {
@Mock @Mock
private SecurityContext expectedContext; private SecurityContext expectedContext;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
@Before @Before
public void setup() { public void setup() {
this.request = new MockHttpServletRequest(); this.request = new MockHttpServletRequest();
mockWebTestUtils(); this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
} }
@After @After
@ -79,9 +78,4 @@ public class SecurityMockMvcRequestPostProcessorsSecurityContextTests {
assertThat(context).isSameAs(this.expectedContext); assertThat(context).isSameAs(this.expectedContext);
} }
private void mockWebTestUtils() {
PowerMockito.spy(WebTestUtils.class);
PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository);
}
} }

View File

@ -23,10 +23,8 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito; import org.mockito.MockedStatic;
import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
@ -40,10 +38,7 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
@PowerMockIgnore({ "javax.security.auth.*", "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*",
"javax.xml.parsers.*" })
public class SecurityMockMvcRequestPostProcessorsTestSecurityContextTests { public class SecurityMockMvcRequestPostProcessorsTestSecurityContextTests {
@Mock @Mock
@ -52,12 +47,16 @@ public class SecurityMockMvcRequestPostProcessorsTestSecurityContextTests {
@Mock @Mock
private SecurityContextRepository repository; private SecurityContextRepository repository;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
private MockHttpServletRequest request; private MockHttpServletRequest request;
@Before @Before
public void setup() { public void setup() {
this.request = new MockHttpServletRequest(); this.request = new MockHttpServletRequest();
mockWebTestUtils(); this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
} }
@After @After
@ -80,9 +79,4 @@ public class SecurityMockMvcRequestPostProcessorsTestSecurityContextTests {
any(HttpServletResponse.class)); any(HttpServletResponse.class));
} }
private void mockWebTestUtils() {
PowerMockito.spy(WebTestUtils.class);
PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository);
}
} }

View File

@ -25,10 +25,8 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito; import org.mockito.MockedStatic;
import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -44,10 +42,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
@PowerMockIgnore({ "javax.security.auth.*", "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*",
"javax.xml.parsers.*" })
public class SecurityMockMvcRequestPostProcessorsUserDetailsTests { public class SecurityMockMvcRequestPostProcessorsUserDetailsTests {
@Captor @Captor
@ -61,10 +56,14 @@ public class SecurityMockMvcRequestPostProcessorsUserDetailsTests {
@Mock @Mock
private UserDetails userDetails; private UserDetails userDetails;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
@Before @Before
public void setup() { public void setup() {
this.request = new MockHttpServletRequest(); this.request = new MockHttpServletRequest();
mockWebTestUtils(); this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
} }
@After @After
@ -82,9 +81,4 @@ public class SecurityMockMvcRequestPostProcessorsUserDetailsTests {
assertThat(context.getAuthentication().getPrincipal()).isSameAs(this.userDetails); assertThat(context.getAuthentication().getPrincipal()).isSameAs(this.userDetails);
} }
private void mockWebTestUtils() {
PowerMockito.spy(WebTestUtils.class);
PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository);
}
} }

View File

@ -28,10 +28,8 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito; import org.mockito.MockedStatic;
import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -48,10 +46,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareOnlyThisForTest(WebTestUtils.class)
@PowerMockIgnore({ "javax.security.auth.*", "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*",
"javax.xml.parsers.*" })
public class SecurityMockMvcRequestPostProcessorsUserTests { public class SecurityMockMvcRequestPostProcessorsUserTests {
@Captor @Captor
@ -68,10 +63,14 @@ public class SecurityMockMvcRequestPostProcessorsUserTests {
@Mock @Mock
private GrantedAuthority authority2; private GrantedAuthority authority2;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
@Before @Before
public void setup() { public void setup() {
this.request = new MockHttpServletRequest(); this.request = new MockHttpServletRequest();
mockWebTestUtils(); this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
} }
@After @After
@ -134,9 +133,4 @@ public class SecurityMockMvcRequestPostProcessorsUserTests {
this.authority2); this.authority2);
} }
private void mockWebTestUtils() {
PowerMockito.spy(WebTestUtils.class);
PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository);
}
} }

View File

@ -23,10 +23,11 @@ dependencies {
testImplementation 'commons-codec:commons-codec' testImplementation 'commons-codec:commons-codec'
testImplementation 'io.projectreactor:reactor-test' testImplementation 'io.projectreactor:reactor-test'
testImplementation 'javax.xml.bind:jaxb-api' testImplementation 'javax.xml.bind:jaxb-api'
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.mockito:mockito-inline'
testImplementation 'org.skyscreamer:jsonassert' testImplementation 'org.skyscreamer:jsonassert'
testImplementation 'org.springframework:spring-webflux' testImplementation 'org.springframework:spring-webflux'
testImplementation 'org.synchronoss.cloud:nio-multipart-parser' testImplementation 'org.synchronoss.cloud:nio-multipart-parser'
testImplementation powerMock2Dependencies
testRuntimeOnly 'org.hsqldb:hsqldb' testRuntimeOnly 'org.hsqldb:hsqldb'
} }

View File

@ -22,11 +22,7 @@ import javax.servlet.http.HttpServletResponse;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
@ -40,7 +36,6 @@ import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -55,9 +50,6 @@ import static org.mockito.Mockito.verify;
* @author Luke Taylor * @author Luke Taylor
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(ReflectionUtils.class)
@PowerMockIgnore("javax.security.auth.*")
public class AbstractRememberMeServicesTests { public class AbstractRememberMeServicesTests {
static User joe = new User("joe", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_A")); static User joe = new User("joe", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_A"));

View File

@ -17,8 +17,6 @@
package org.springframework.security.web.authentication.session; package org.springframework.security.web.authentication.session;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
@ -28,7 +26,6 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Rob Winch * @author Rob Winch
* *
*/ */
@RunWith(PowerMockRunner.class)
public class ChangeSessionIdAuthenticationStrategyTests { public class ChangeSessionIdAuthenticationStrategyTests {
@Test @Test

View File

@ -29,8 +29,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.FilterChainProxy;
@ -48,8 +47,7 @@ import static org.mockito.Mockito.verify;
* @author Rob Winch * @author Rob Winch
* *
*/ */
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareOnlyThisForTest(Logger.class)
public class DebugFilterTests { public class DebugFilterTests {
@Captor @Captor

View File

@ -18,14 +18,10 @@ package org.springframework.security.web.header.writers;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -33,8 +29,6 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Rob Winch * @author Rob Winch
* *
*/ */
@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(ReflectionUtils.class)
public class CacheControlHeadersWriterTests { public class CacheControlHeadersWriterTests {
private MockHttpServletRequest request; private MockHttpServletRequest request;

View File

@ -32,8 +32,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.Captor; import org.mockito.Captor;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
@ -48,7 +47,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@ -69,8 +67,7 @@ import static org.mockito.Mockito.verifyZeroInteractions;
* @author Rob Winch * @author Rob Winch
* @author Eddú Meléndez * @author Eddú Meléndez
*/ */
@RunWith(PowerMockRunner.class) @RunWith(MockitoJUnitRunner.class)
@PrepareForTest(ClassUtils.class)
public class SecurityContextHolderAwareRequestFilterTests { public class SecurityContextHolderAwareRequestFilterTests {
@Captor @Captor
@ -176,8 +173,6 @@ public class SecurityContextHolderAwareRequestFilterTests {
@Test @Test
public void loginWithExistingUser() throws Exception { public void loginWithExistingUser() throws Exception {
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(expectedAuth); SecurityContextHolder.getContext().setAuthentication(expectedAuth);
assertThatExceptionOfType(ServletException.class).isThrownBy( assertThatExceptionOfType(ServletException.class).isThrownBy(
() -> wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials()))); () -> wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials())));