();
final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (classFoundInClassloader(LastControl.class, systemClassLoader)) {
loaders.add(systemClassLoader);
}
if (classFoundInClassloader(LastControl.class, contextClassLoader)) {
loaders.add(contextClassLoader);
}
return loaders;
}
private boolean classFoundInClassloader(Class> cls, ClassLoader classLoader) {
try {
Class.forName(cls.getName(), false, classLoader);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/annotation/Mock.java
================================================
package org.powermock.api.easymock.annotation;
import org.powermock.core.classloader.annotations.PowerMockListener;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation can be placed on those fields in your test class that should
* be mocked. This eliminates the need to setup and tear-down mocks manually
* which minimizes repetitive test code and makes the test more readable. In
* order for PowerMock to control the life-cycle of the mocks you must supply
* the {@link PowerMockListener} annotation to the class-level of the test case.
* For example:
*
*
* ...
* @PowerMockListener(AnnotationEnabler.class)
* public class PersonServiceTest {
*
* @Mock
* private PersonDao personDaoMock;
*
* private PersonService classUnderTest;
*
* @Before
* public void setUp() {
* classUnderTest = new PersonService(personDaoMock);
* }
* ...
* }
*
*
*
* Note that you can also create partial mocks by using the annotation. Let's
* say that the PersonService has a method called "getPerson" and another method
* called "savePerson" and these are the only two methods that you'd like to
* mock. Rewriting the previous example to accommodate this will give us the
* following test:
*
*
* ...
* @PowerMockListener(AnnotationEnabler.class)
* public class PersonServiceTest {
*
* @Mock({"getPerson", "savePerson"})
* private PersonDao personDaoMock;
*
* private PersonService classUnderTest;
*
* @Before
* public void setUp() {
* classUnderTest = new PersonService(personDaoMock);
* }
* ...
* }
*
*
*/
@Target( { ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Mock {
String[] value() default "";
/**
* Name of the test subject field to which this mock will be assigned. Use to disambiguate the case where
* a mock may be assigned to multiple fields of the same type.
* When set, this mock will be assigned to the given field name in any test subject with a matching field name.
* If not set, injection is to all type-compatible fields in all test subjects.
* A given field name may only be used once, and there must be a matching field in at least one test subject.
*
* @return name of the field to inject to
**/
String fieldName() default "";
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/annotation/MockNice.java
================================================
package org.powermock.api.easymock.annotation;
import org.powermock.core.classloader.annotations.PowerMockListener;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation can be placed on those fields in your test class that should
* be mocked in a nice manner (i.e. by default allows all method calls and
* returns appropriate empty values (0, {@code null} or {@code false}
* )). This eliminates the need to setup and tear-down mocks manually which
* minimizes repetitive test code and makes the test more readable. In order for
* PowerMock to control the life-cycle of the mocks you must supply the
* {@link PowerMockListener} annotation to the class-level of the test case. For
* example when using the EasyMock API:
*
*
* @PowerMockListener(EasyMockAnnotationEnabler.class)
* public class PersonServiceTest {
*
* @MockNice
* private PersonDao personDaoMock;
*
* private PersonService classUnderTest;
*
* @Before
* public void setUp() {
* classUnderTest = new PersonService(personDaoMock);
* }
* ...
* }
*
*
*
* Note that you can also create partial mocks by using the annotation. Let's
* say that the PersonService has a method called "getPerson" and another method
* called "savePerson" and these are the only two methods that you'd like to
* mock. Rewriting the previous example to accommodate this will give us the
* following test:
*
*
* @PowerMockListener(EasyMockAnnotationEnabler.class)
* public class PersonServiceTest {
*
* @MockNice({"getPerson", "savePerson"})
* private PersonDao personDaoMock;
*
* private PersonService classUnderTest;
*
* @Before
* public void setUp() {
* classUnderTest = new PersonService(personDaoMock);
* }
* ...
* }
*
*
*
*/
@Target( { ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MockNice {
String[] value() default "";
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/annotation/MockStrict.java
================================================
package org.powermock.api.easymock.annotation;
import org.powermock.core.classloader.annotations.PowerMockListener;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation can be placed on those fields in your test class that should
* be mocked in a strict manner (i.e. the order of method calls are checked).
* This eliminates the need to setup and tear-down mocks manually which
* minimizes repetitive test code and makes the test more readable. In order for
* PowerMock to control the life-cycle of the mocks you must supply the
* {@link PowerMockListener} annotation to the class-level of the test case. For
* example when using the EasyMock API:
*
*
* @PowerMockListener(EasyMockAnnotationEnabler.class)
* public class PersonServiceTest {
*
* @MockStrict
* private PersonDao personDaoMock;
*
* private PersonService classUnderTest;
*
* @Before
* public void setUp() {
* classUnderTest = new PersonService(personDaoMock);
* }
* ...
* }
*
*
*
* Note that you can also create partial mocks by using the annotation. Let's
* say that the PersonService has a method called "getPerson" and another method
* called "savePerson" and these are the only two methods that you'd like to
* mock. Rewriting the previous example to accommodate this will give us the
* following test:
*
*
* @PowerMockListener(EasyMockAnnotationEnabler.class)
* public class PersonServiceTest {
*
* @MockStrict({"getPerson", "savePerson"})
* private PersonDao personDaoMock;
*
* private PersonService classUnderTest;
*
* @Before
* public void setUp() {
* classUnderTest = new PersonService(personDaoMock);
* }
* ...
* }
*
*
*
*/
@Target( { ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MockStrict {
String[] value() default "";
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/invocationcontrol/EasyMockMethodInvocationControl.java
================================================
/*
* 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
*
* http://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.powermock.api.easymock.internal.invocationcontrol;
import org.easymock.MockType;
import org.easymock.internal.MockInvocationHandler;
import org.easymock.internal.MocksControl;
import org.powermock.core.spi.MethodInvocationControl;
import org.powermock.reflect.internal.WhiteboxImpl;
import java.lang.reflect.Method;
import java.util.Set;
/**
* The default implementation of the {@link MethodInvocationControl} interface.
*/
public class EasyMockMethodInvocationControl implements MethodInvocationControl {
private MockInvocationHandler invocationHandler;
private Set mockedMethods;
private T mockInstance;
private boolean hasReplayed;
private boolean hasVerified;
/**
* Initializes internal state.
*
* @param invocationHandler The mock invocation handler to be associated with this
* instance.
* @param methodsToMock The methods that are mocked for this instance. If
* {@code methodsToMock} is null all methods for the
* {@code invocationHandler} are considered to be mocked.
* @param mockInstance The actual mock instance. May be {@code null}. Even
* though the mock instance may not be used it's needed to keep a
* reference to this object otherwise it may be garbage collected
* in some situations. For example when mocking static methods we
* don't return the mock object and thus it will be garbage
* collected (and thus the finalize method will be invoked which
* will be caught by the proxy and the test will fail because we
* haven't setup expectations for this method) because then that
* object has no reference. In order to avoid this we keep a
* reference to this instance here.
*/
public EasyMockMethodInvocationControl(MockInvocationHandler invocationHandler, Set methodsToMock, T mockInstance) {
if (invocationHandler == null) {
throw new IllegalArgumentException("Invocation Handler cannot be null.");
}
this.invocationHandler = invocationHandler;
this.mockedMethods = methodsToMock;
this.mockInstance = mockInstance;
}
/**
* Initializes internal state.
*
* @param invocationHandler The mock invocation handler to be associated with this
* instance.
* @param methodsToMock The methods that are mocked for this instance. If
* {@code methodsToMock} is null all methods for the
* {@code invocationHandler} are considered to be mocked.
*/
public EasyMockMethodInvocationControl(MockInvocationHandler invocationHandler, Set methodsToMock) {
this(invocationHandler, methodsToMock, null);
}
@Override
public boolean isMocked(Method method) {
return mockedMethods == null || (mockedMethods != null && mockedMethods.contains(method));
}
@Override
public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
return invocationHandler.invoke(mockInstance == null ? proxy : mockInstance, method, arguments);
}
public MockType getMockType() {
final MocksControl control = invocationHandler.getControl();
if (WhiteboxImpl.getFieldsOfType(control, MockType.class).isEmpty()) {
// EasyMock is of version 3.2+
final MockType mockType = WhiteboxImpl.getInternalState(control, MockType.class);
switch (mockType) {
case DEFAULT:
return MockType.DEFAULT;
case NICE:
return MockType.NICE;
case STRICT:
return MockType.STRICT;
default:
throw new IllegalStateException("PowerMock doesn't seem to work with the used EasyMock version. Please report to the PowerMock mailing list");
}
} else {
return WhiteboxImpl.getInternalState(control, MockType.class);
}
}
@Override
public synchronized Object replay(Object... mocks) {
// Silently ignore replay if someone has replayed the mock before.
if (!hasReplayed) {
invocationHandler.getControl().replay();
hasReplayed = true;
}
return null;
}
public synchronized Object verify(Object... mocks) {
// Silently ignore verify if someone has verified the mock before.
if (!hasVerified) {
invocationHandler.getControl().verify();
hasVerified = true;
}
return null;
}
@Override
public synchronized Object reset(Object... mocks) {
invocationHandler.getControl().reset();
hasReplayed = false;
hasVerified = false;
return null;
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/invocationcontrol/EasyMockNewInvocationControl.java
================================================
/*
* 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
*
* http://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.powermock.api.easymock.internal.invocationcontrol;
import org.easymock.EasyMock;
import org.easymock.IExpectationSetters;
import org.easymock.MockType;
import org.easymock.internal.MocksControl;
import org.powermock.core.MockRepository;
import org.powermock.core.spi.NewInvocationControl;
import org.powermock.core.spi.support.InvocationSubstitute;
import org.powermock.reflect.internal.WhiteboxImpl;
import java.lang.reflect.Constructor;
public class EasyMockNewInvocationControl implements NewInvocationControl> {
private final InvocationSubstitute substitute;
private final Class subsitutionType;
private boolean hasReplayed;
private boolean hasVerified;
public EasyMockNewInvocationControl(InvocationSubstitute substitute, Class type) {
if (substitute == null) {
throw new IllegalArgumentException("Internal error: substitute cannot be null.");
}
this.subsitutionType = type;
this.substitute = substitute;
}
@Override
public Object invoke(Class> type, Object[] args, Class>[] sig) throws Exception {
Constructor> constructor = WhiteboxImpl.getConstructor(type, sig);
if (constructor.isVarArgs()) {
/*
* Get the last argument because this contains the actual varargs
* arguments.
*/
int length = constructor.getParameterTypes().length;
args = (Object[]) args[length-1];
}
try {
final MockType mockType = ((EasyMockMethodInvocationControl>) MockRepository.getInstanceMethodInvocationControl(substitute))
.getMockType();
Object result = substitute.performSubstitutionLogic(args);
if (result == null) {
if (mockType == MockType.NICE) {
result = EasyMock.createNiceMock(subsitutionType);
} else {
throw new IllegalStateException("Must replay class " + type.getName() + " to get configured expectation.");
}
}
return result;
} catch (AssertionError e) {
NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type);
}
// Won't happen
return null;
}
@Override
public IExpectationSetters expectSubstitutionLogic(Object... arguments) throws Exception {
return EasyMock.expect(substitute.performSubstitutionLogic(arguments));
}
@Override
public synchronized Object replay(Object... mocks) {
if (!hasReplayed) {
EasyMock.replay(substitute);
hasReplayed = true;
}
return null;
}
public synchronized Object verify(Object... mocks) {
if (!hasVerified) {
EasyMock.verify(substitute);
hasVerified = true;
}
return null;
}
@Override
public synchronized Object reset(Object... mocks) {
EasyMock.reset(substitute);
hasReplayed = false;
hasVerified = false;
return null;
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/invocationcontrol/NewInvocationControlAssertionError.java
================================================
package org.powermock.api.easymock.internal.invocationcontrol;
import org.powermock.core.spi.support.InvocationSubstitute;
import java.util.regex.Matcher;
public class NewInvocationControlAssertionError {
public static void throwAssertionErrorForNewSubstitutionFailure(AssertionError oldError, Class> type) {
/*
* We failed to verify the new substitution mock. This happens when, for
* example, the user has done something like
* expectNew(MyClass.class).andReturn(myMock).times(3) when in fact an
* instance of MyClass has been created less or more times than 3.
*/
String message = oldError.getMessage();
final String newSubsitutionMethodName = InvocationSubstitute.class.getDeclaredMethods()[0].getName();
final String className = InvocationSubstitute.class.getSimpleName();
message = message.replaceAll(className+"."+newSubsitutionMethodName, Matcher.quoteReplacement(type.getName()));
message = message.replaceAll("method", "constructor");
throw new AssertionError(message);
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/MockStrategy.java
================================================
package org.powermock.api.easymock.internal.mockstrategy;
import org.easymock.IMocksControl;
public interface MockStrategy {
IMocksControl createMockControl(Class> type);
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/AbstractMockStrategyBase.java
================================================
package org.powermock.api.easymock.internal.mockstrategy.impl;
import org.easymock.IMocksControl;
import org.easymock.internal.MocksControl;
import org.easymock.MockType;
import org.powermock.api.easymock.internal.mockstrategy.MockStrategy;
/**
* Base class that should be used by all mock strategies. Enables mocking of
* signed classes.
*/
public abstract class AbstractMockStrategyBase implements MockStrategy {
private final MockType mockType;
public AbstractMockStrategyBase(MockType mockType) {
if (mockType == null) {
throw new IllegalArgumentException("Internal error: mockType cannot be null");
}
this.mockType = mockType;
}
@Override
public IMocksControl createMockControl(Class> type) {
return new MocksControl(mockType);
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/DefaultMockStrategy.java
================================================
package org.powermock.api.easymock.internal.mockstrategy.impl;
import org.easymock.MockType;
public class DefaultMockStrategy extends AbstractMockStrategyBase {
public DefaultMockStrategy() {
super(MockType.DEFAULT);
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/NiceMockStrategy.java
================================================
package org.powermock.api.easymock.internal.mockstrategy.impl;
import org.easymock.MockType;
public class NiceMockStrategy extends AbstractMockStrategyBase {
public NiceMockStrategy() {
super(MockType.NICE);
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/StrictMockStrategy.java
================================================
package org.powermock.api.easymock.internal.mockstrategy.impl;
import org.easymock.MockType;
public class StrictMockStrategy extends AbstractMockStrategyBase {
public StrictMockStrategy() {
super(MockType.STRICT);
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/AbstractEasyMockLogPolicyBase.java
================================================
/*
* 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
*
* http://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.powermock.api.easymock.mockpolicies;
import org.powermock.core.spi.PowerMockPolicy;
import org.powermock.mockpolicies.MockPolicyClassLoadingSettings;
import org.powermock.mockpolicies.MockPolicyInterceptionSettings;
import org.powermock.mockpolicies.support.LogPolicySupport;
import java.lang.reflect.Method;
import static org.easymock.EasyMock.makeThreadSafe;
import static org.powermock.api.easymock.PowerMock.createNiceMock;
/**
* A base class for EasyMock log policies.
*/
abstract class AbstractEasyMockLogPolicyBase implements PowerMockPolicy {
@Override
public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) {
settings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(getFullyQualifiedNamesOfClassesToLoadByMockClassloader());
}
@Override
public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) {
LogPolicySupport support = new LogPolicySupport();
Method[] loggerFactoryMethods = support.getLoggerMethods(getLoggerFactoryClassName(), getLoggerMethodName(), getLogFrameworkName());
Class> loggerType = null;
try {
loggerType = support.getType(getLoggerClassToMock(), getLogFrameworkName());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
final Object loggerMock = createNiceMock(loggerType);
// Allow the mock to be used in a multi-threaded environment
makeThreadSafe(loggerMock, true);
for (Method method : loggerFactoryMethods) {
settings.stubMethod(method, loggerMock);
}
}
/**
* @return The name of the methods in the Logger Factory that should return
* a mock upon invocation.
*/
protected abstract String getLoggerMethodName();
/**
* @return The fully-qualified class name of the Logger Factory that
* contains the methods that should return a mock upon invocation.
*/
protected abstract String getLoggerFactoryClassName();
/**
* @return The fully-qualified class name of the class that should be
* mocked. The mock instance of this class will then be returned
* each time a specified method in the Logger Factory is invoked.
*/
protected abstract String getLoggerClassToMock();
/**
* @return The name of the log framework. Used in error messages, for
* example if the {@link #getLoggerFactoryClassName()} cannot be
* found in the classpath.
*/
protected abstract String getLogFrameworkName();
/**
* @return The fully-qualified names of the classes that should be loaded by
* the mock classloader.
*/
protected abstract String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader();
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/JclMockPolicy.java
================================================
/*
* 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
*
* http://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.powermock.api.easymock.mockpolicies;
/**
* A Jakarta Commons-Logging (JCL) mock policy. This mock policy deals with
* solving JCL related mocking issues. It takes care of loading all concerned
* JCL classes through the correct class-loader and automatically prepares and
* injects logger instances. This policy does the following:
*
* - Prepares all classes in the org.apache.commons.logging for test
* as well as org.apache.log4j.Appender and
* org.apache.log4j.xml.DOMConfigurator.
* - All calls to the
* org.apache.commons.logging.LogFactory#getLog(..) methods are
* intercepted and returns a nice mock of type
* org.apache.commons.logging.Log.
*
*/
public class JclMockPolicy extends AbstractEasyMockLogPolicyBase {
/**
* Loads all log4j classes with the mock classloader.
*/
protected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() {
return new String[] { "org.apache.commons.logging.*", "org.apache.log4j.Appender", "org.apache.log4j.xml.DOMConfigurator" };
}
@Override
protected String getLogFrameworkName() {
return "commons-logging";
}
@Override
protected String getLoggerClassToMock() {
return "org.apache.commons.logging.Log";
}
@Override
protected String getLoggerFactoryClassName() {
return "org.apache.commons.logging.LogFactory";
}
@Override
protected String getLoggerMethodName() {
return "getLog";
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/Log4jMockPolicy.java
================================================
/*
* 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
*
* http://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.powermock.api.easymock.mockpolicies;
/**
* A log4j mock policy. This mock policy deals with solving log4j related
* mocking issues. It takes care of loading all concerned log4j classes through
* the correct class-loader and automatically prepares and injects logger
* instances. This policy does the following:
*
* - Prepares all log4j classes and interfaces for testing.
* - All calls to the org.apache.log4j.Logger#getLogger(..) methods
* are intercepted and returns a nice mock of type
* org.apache.log4j.Logger.
*
*/
public class Log4jMockPolicy extends AbstractEasyMockLogPolicyBase {
private static final String LOGGER_CLASS = "org.apache.log4j.Logger";
/**
* Loads all log4j classes with the mock classloader.
*/
@Override
protected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() {
return new String[] { "org.apache.log4j.*" };
}
@Override
protected String getLogFrameworkName() {
return "log4j";
}
@Override
protected String getLoggerClassToMock() {
return LOGGER_CLASS;
}
@Override
protected String getLoggerFactoryClassName() {
return LOGGER_CLASS;
}
@Override
protected String getLoggerMethodName() {
return "getLogger";
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/Slf4jMockPolicy.java
================================================
/*
* 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
*
* http://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.powermock.api.easymock.mockpolicies;
/**
* An slf4j mock policy. This mock policy deals with solving slf4j related
* mocking issues. It takes care of loading all concerned slf4j and log4j
* classes through the correct class-loader and automatically prepares and
* injects logger instances. This policy does the following:
*
* - Prepares org.apache.log4j.Appender,
* org.slf4j.LoggerFactory and
* org.apache.log4j.xml.DOMConfigurator for testing.
* - All calls to the org.slf4j.LoggerFactory#getLogger(..) methods
* are intercepted and returns a nice mock of type org.slf4j.Logger.
*
*/
public class Slf4jMockPolicy extends AbstractEasyMockLogPolicyBase {
@Override
protected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() {
return new String[] { "org.apache.log4j.Appender", "org.slf4j.LoggerFactory", "org.apache.log4j.xml.DOMConfigurator" };
}
@Override
protected String getLogFrameworkName() {
return "slf4j";
}
@Override
protected String getLoggerClassToMock() {
return "org.slf4j.Logger";
}
@Override
protected String getLoggerFactoryClassName() {
return "org.slf4j.LoggerFactory";
}
@Override
protected String getLoggerMethodName() {
return "getLogger";
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/powermocklistener/AnnotationEnabler.java
================================================
/*
* 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
*
* http://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.powermock.api.easymock.powermocklistener;
import org.powermock.api.easymock.annotation.MockNice;
import org.powermock.api.easymock.annotation.MockStrict;
/**
* Before each test method all fields annotated with {@link org.powermock.api.easymock.annotation.Mock},
* {@link MockNice} or {@link MockStrict} will have mock objects created for
* them and injected to the fields.
*
* @deprecated Test Runners uses an annotation enabling listener per default
* since version 1.3. You should just remove this listener.
*/
@Deprecated
public class AnnotationEnabler extends org.powermock.api.extension.listener.AnnotationEnabler {
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/InjectFieldSearcher.java
================================================
/*
* Copyright 2016 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
*
* http://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.powermock.api.extension;
import org.powermock.api.extension.listener.MockMetadata;
import java.lang.reflect.Field;
/**
*
*/
public interface InjectFieldSearcher {
Field findField(Object instance, MockMetadata mockMetadata);
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/agent/JavaAgentFrameworkRegisterImpl.java
================================================
/*
* Copyright 2016 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
*
* http://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.powermock.api.extension.agent;
import org.powermock.core.agent.JavaAgentClassRegister;
import org.powermock.core.agent.JavaAgentFrameworkRegister;
/**
* Implementation of JavaAgentFrameworkRegister for EasyMock framework.
*/
public class JavaAgentFrameworkRegisterImpl implements JavaAgentFrameworkRegister {
@Override
public void set(JavaAgentClassRegister javaAgentClassRegister) {
}
@Override
public void clear() {
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java
================================================
/*
* 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
*
* http://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.powermock.api.extension.listener;
import org.powermock.api.easymock.EasyMockConfiguration;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.api.easymock.annotation.MockNice;
import org.powermock.api.easymock.annotation.MockStrict;
import org.powermock.core.spi.listener.AnnotationEnablerListener;
import org.powermock.core.spi.support.AbstractPowerMockTestListenerBase;
import org.powermock.reflect.Whitebox;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
*
* Before each test method all fields annotated with
* {@link Mock}, {@link org.powermock.api.easymock.annotation.Mock}, {@link org.easymock.Mock}
* {@link MockNice} or {@link MockStrict} will have mock objects created for
* them and injected to the fields.
*
*
* Also all fields annotated with {@link org.easymock.TestSubject} will be processed and mocks are injected to fields
* object, if these fields not null.
*
*
* It will only inject to fields that haven't been set before (i.e that are
* {@code null}).
*
*
* @see org.powermock.api.easymock.annotation.Mock
* @see org.easymock.Mock
* @see org.easymock.TestSubject
*
*/
@SuppressWarnings({"deprecation", "JavadocReference"})
public class AnnotationEnabler extends AbstractPowerMockTestListenerBase implements AnnotationEnablerListener {
@SuppressWarnings("unchecked")
public Class extends Annotation>[] getMockAnnotations() {
return new Class[]{Mock.class, MockNice.class, MockStrict.class};
}
@Override
public void beforeTestMethod(Object testInstance, Method method, Object[] arguments) throws Exception {
EasyMockConfiguration easyMockConfiguration = EasyMockConfiguration.getConfiguration();
if (!easyMockConfiguration.isReallyEasyMock()) {
// Easymock API could be used as depends for JMock.
return;
}
// first emulate default EasyMockRunner behavior
if (easyMockConfiguration.isInjectMocksSupported()) {
Whitebox.invokeMethod(Class.forName("org.easymock.EasyMockSupport"), "injectMocks", testInstance);
}
// then inject in empty fields mock created via PowerMock
getEasyMockAnnotationSupport(testInstance).injectMocks();
}
@SuppressWarnings("WeakerAccess")
protected EasyMockAnnotationSupport getEasyMockAnnotationSupport(Object testInstance) {
return new EasyMockAnnotationSupport(testInstance);
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationGlobalMetadata.java
================================================
/*
* Copyright 2016 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
*
* http://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.powermock.api.extension.listener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
*/
class AnnotationGlobalMetadata {
private final List qualifiedInjections = new ArrayList(5);
private final List unqualifiedInjections = new ArrayList(5);
private final Set qualifiers = new HashSet();
public List getQualifiedInjections() {
return qualifiedInjections;
}
public List getUnqualifiedInjections() {
return unqualifiedInjections;
}
public void add(List mocksMetadata) {
for (MockMetadata mockMetadata : mocksMetadata) {
add(mockMetadata);
}
}
private void add(MockMetadata mockMetadata) {
String qualifier = mockMetadata.getQualifier();
if (qualifier.length() != 0) {
blockDuplicateQualifiers(qualifier);
qualifiedInjections.add(mockMetadata);
} else {
unqualifiedInjections.add(mockMetadata);
}
}
private void blockDuplicateQualifiers(String qualifier) {
if (!qualifiers.add(qualifier)) {
throw new RuntimeException(String.format("At least two mocks have fieldName qualifier '%s'", qualifier));
}
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreator.java
================================================
/*
* Copyright 2016 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
*
* http://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.powermock.api.extension.listener;
import java.lang.reflect.Method;
/**
*
*/
interface AnnotationMockCreator {
Object createMockInstance(final Class> type, final Method[] methods);
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreatorFactory.java
================================================
/*
* Copyright 2016 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
*
* http://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.powermock.api.extension.listener;
import java.lang.reflect.Method;
import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.createNiceMock;
import static org.powermock.api.easymock.PowerMock.createStrictMock;
/**
*
*/
class AnnotationMockCreatorFactory {
public AnnotationMockCreator createDefaultMockCreator() {
return new AnnotationMockCreator() {
@Override
public Object createMockInstance(Class> type, Method[] methods) {
return createMock(type, methods);
}
};
}
public AnnotationMockCreator createNiceMockCreator() {
return new AnnotationMockCreator() {
@Override
public Object createMockInstance(Class> type, Method[] methods) {
return createNiceMock(type, methods);
}
};
}
public AnnotationMockCreator createStrictMockCreator() {
return new AnnotationMockCreator() {
@Override
public Object createMockInstance(Class> type, Method[] methods) {
return createStrictMock(type, methods);
}
};
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockMetadata.java
================================================
/*
* Copyright 2016 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
*
* http://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.powermock.api.extension.listener;
import org.powermock.reflect.Whitebox;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
@SuppressWarnings("WeakerAccess")
public class AnnotationMockMetadata implements MockMetadata {
private final Class> type;
private final Method[] methods;
private final String qualifier;
private final Class extends Annotation> annotation;
private final Annotation annotationInstance;
private final String fieldName;
private Object mock;
public AnnotationMockMetadata(Class extends Annotation> annotation, Field field) throws
Exception {
this.annotation = annotation;
this.annotationInstance = field.getAnnotation(annotation);
this.type = field.getType();
this.fieldName = field.getName();
this.methods = getMethod();
this.qualifier = findQualifier();
}
private String findQualifier() {
String fieldName = "";
try {
fieldName = Whitebox.invokeMethod(annotationInstance, "fieldName");
} catch (Exception e) {
// do nothing, because it means that Mock annotation doesn't support qualifier. S
// ee org.easymock.Mock.fieldName
}
if (fieldName.length() == 0) {
return "";
} else {
return fieldName;
}
}
@Override
public String getFieldName() {
return fieldName;
}
@Override
public String getQualifier() {
return qualifier;
}
@Override
public Class extends Annotation> getAnnotation() {
return annotation;
}
@Override
public Class> getType() {
return type;
}
@Override
public Method[] getMethods() {
return methods;
}
private Method[] getMethod() throws Exception {
final String[] value = Whitebox.invokeMethod(annotationInstance, "value");
if (value.length != 1 || !"".equals(value[0])) {
return Whitebox.getMethods(type, value);
}
return null;
}
@Override
public Object getMock() {
return mock;
}
@Override
public void setMock(Object mock) {
this.mock = mock;
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
AnnotationMockMetadata that = (AnnotationMockMetadata) o;
if (type != null ? !type.equals(that.type) : that.type != null) { return false; }
// Probably incorrect - comparing Object[] arrays with Arrays.equals
return Arrays.equals(methods, that.methods) && (qualifier != null ? qualifier.equals(that.qualifier) : that.qualifier == null);
}
@Override
public int hashCode() {
int result = type != null ? type.hashCode() : 0;
result = 31 * result + Arrays.hashCode(methods);
result = 31 * result + (qualifier != null ? qualifier.hashCode() : 0);
return result;
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockScanner.java
================================================
/*
* Copyright 2016 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
*
* http://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.powermock.api.extension.listener;
import org.powermock.reflect.Whitebox;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
class AnnotationMockScanner {
private final Class extends Annotation> annotation;
public AnnotationMockScanner(Class extends Annotation> annotation) {
this.annotation = annotation;
}
public List scan(Object instance) throws Exception {
final List mocksMetadata = new ArrayList();
final Set fields = getFields(instance);
for (Field field : fields) {
if (field.get(instance) != null) {
continue;
}
mocksMetadata.add(new AnnotationMockMetadata(annotation, field));
}
return mocksMetadata;
}
@SuppressWarnings("unchecked")
private Set getFields(Object instance) {
final Set fields;
if (annotation != null) {
fields = Whitebox.getFieldsAnnotatedWith(instance, annotation);
}else{
fields = Whitebox.getAllInstanceFields(instance);
}
return fields;
}
}
================================================
FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/DefaultInjectFieldSearcher.java
================================================
/*
* Copyright 2016 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
*
* http://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.powermock.api.extension.listener;
import org.powermock.api.extension.InjectFieldSearcher;
import org.powermock.reflect.Whitebox;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
/**
*
*/
@SuppressWarnings("unchecked")
class DefaultInjectFieldSearcher implements InjectFieldSearcher {
@Override
public Field findField(Object instance, MockMetadata mockMetadata) {
Set candidates = Whitebox.getFieldsAnnotatedWith(instance, mockMetadata.getAnnotation());
if (candidates.size() == 1) {
return candidates.iterator().next();
}
candidates = filterByQualifier(candidates, mockMetadata.getQualifier());
if (candidates.size() == 1) {
return candidates.iterator().next();
}
candidates = filterByType(candidates, mockMetadata.getType());
if (candidates.size() == 1) {
return candidates.iterator().next();
}
candidates = filterByFieldName(candidates, mockMetadata.getFieldName());
if (candidates.size() == 1) {
return candidates.iterator().next();
}
return null;
}
private Set filterByFieldName(final Set