Giter Site home page Giter Site logo

powermock / powermock Goto Github PK

View Code? Open in Web Editor NEW
4.1K 167.0 582.0 5.81 MB

PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

License: Apache License 2.0

Java 100.00%
java testability testing mocking mocking-framework

powermock's Introduction

PowerMock

Build Status Maven Central Download Javadoc

Writing unit tests can be hard and sometimes good design has to be sacrificed for the sole purpose of testability. Often testability corresponds to good design, but this is not always the case. For example final classes and methods cannot be used, private methods sometimes need to be protected or unnecessarily moved to a collaborator, static methods should be avoided completely and so on simply because of the limitations of existing frameworks.

PowerMock is a framework that extends other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more. By using a custom classloader no changes need to be done to the IDE or continuous integration servers which simplifies adoption. Developers familiar with the supported mock frameworks will find PowerMock easy to use, since the entire expectation API is the same, both for static methods and constructors. PowerMock aims to extend the existing API's with a small number of methods and annotations to enable the extra features. Currently PowerMock supports EasyMock and Mockito.

When writing unit tests it is often useful to bypass encapsulation and therefore PowerMock includes several features that simplifies reflection specifically useful for testing. This allows easy access to internal state, but also simplifies partial and private mocking.

Please note that PowerMock is mainly intended for people with expert knowledge in unit testing. Putting it in the hands of junior developers may cause more harm than good.

News

  • 2019-04-21: PowerMock 2.0.2 has been released and is avaliable in Maven Central. The release includes fixes for issue with PowerMock JavaAgent and the latest JDK and a security issue with the build script.
  • 2019-01-07: PowerMock 2.0.0 has been released. Main changes: offical supporting Mockito 2.x and dropping supporting Mockito 1.x. This release also supports Java 9. Other change read in release notes.
  • 2017-08-12: PowerMock 1.7.1 has been released with one, but significant change: the old API for verifying static mock has been deprecated and a new one has been added. Old API will be removed in version PowerMock 2.0 due to incompatibility with Mockito Public API.
  • 2017-06-16: PowerMock 1.7.0 has been released with support for Mockito 2 (not only beta versions) and new features such as global @PowerMockIgnore as well as bug fixes and other improvements. See release notes and change log for details.
  • 2017-02-03: Johan blogs about how to mock slf4j with PowerMock at his blog

Older News

Documentation

Contributing to PowerMock

Please, read the guideline for a new contributor before start.

Support and discussion

Join the mailing-list here for questions, feedback and support.

powermock's People

Contributors

astafev avatar beegee1 avatar bsodzik avatar civanyp avatar darxriggs avatar dependabot[bot] avatar eraonel avatar henri-tremblay avatar hsynkrtl avatar ijuma avatar johanhaleby avatar johnjohndoe avatar kaipe avatar kovalskyi avatar leventov avatar occho avatar peerhartmann avatar podarsmarty avatar powermock-release-tools avatar sam-ma avatar ssaip avatar stefanbirkner avatar stevegilbert23 avatar sullis avatar thekingn0thing avatar timomeinen avatar valery1707 avatar valfirst avatar vampire avatar wwilk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

powermock's Issues

Create a compatibility junit runner

From [email protected] on September 23, 2008 13:05:18

We should create a "compatibility" runner for JUnit 4 and perhaps JUnit 3.
This means a Junit runner without any chunking. The chunking is tightly
coupled to internal Junit4 functionality and for custom versions of JUnit
our chunking mechanism will fail (for example in the Eclipse JUnit
version). Using a compatibility runner it would be possible to launch
PowerMock (without chunking support) with custom JUnit versions.

Original issue: http://code.google.com/p/powermock/issues/detail?id=16

doInvokeMethod method in PowerMock should treat the InvokationTargetException separately

From [email protected] on October 01, 2008 13:46:29

Right now the doInvokeMethod catches all exceptions and wrap them in a RTE.
This is wrong. The InvokationTargetException should be caught explicitly
and the cause of this exceptions should be thrown instead. This to avoid
error stacks like this:

java.lang.RuntimeException: Failed to invoke method 'assertLogFileSet'.
Reason was: 'null'.
at org.powermock.PowerMock.doInvokeMethod(PowerMock.java:1123)
at org.powermock.PowerMock.expectVoid(PowerMock.java:723)
at
se.mayapp.TargetPersistenceManagerTest.testGetLogFileList(TargetPersistenceManagerTest.java:454)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:162)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:119)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:112)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:110)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:74)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:43)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.powermock.PowerMock.doInvokeMethod(PowerMock.java:1121)
... 26 more
Caused by: java.lang.IllegalStateException: You need to set the log path
before using the target persistence manager.
at
se.mayapp.TargetPersistenceManager.assertLogFileSet(TargetPersistenceManager.java:123)
... 31 more

I.e. the actual exception should be "java.lang.IllegalStateException: You
need to set the log path before using the target persistence manager."

Original issue: http://code.google.com/p/powermock/issues/detail?id=19

Fail to mock class that directly extends java.lang.Object

From [email protected] on October 24, 2008 15:05:11

The new constructor suppression algorithm doesn't work for classes that
directly extend from java.lang.Object since Object doesn't contain a ctor
with with argument IndicateReloadClass. We must change the implementation
in the MainMockTransformers' edit(ConstructorCall c) method to check if the
super class is of type Object before defering the call.

Original issue: http://code.google.com/p/powermock/issues/detail?id=38

WhiteBox.getMethod(..) should also return protected and package-private methods.

From [email protected] on October 28, 2008 16:25:52

If we have a class like this:

public final class SomeHelper {

private SomeHelper() {

}

static class MyPlugin extends MyCorePlugin {
    public MyPlugin() {
        setLogManager(new MockLogManager());
    }  
}

...

}

and load the classes are loaded from our classloader the MockGateway
performs a check, suppressMethod.contains(Whitebox.getMethod(objectType,
methodName, sig)), for the MyPlugin invokation of the setLogManager method.
However if setLogManager is protected the Whitebox.getMethod(..) won't find
the method because it's neither public or private. We need to address this!!

Original issue: http://code.google.com/p/powermock/issues/detail?id=49

Generate binary release

From [email protected] on September 03, 2008 17:06:22

Automatically generate all binary releases from maven. We want to have
pre-packaged jar files for powermock-junit3, powermock-junit4-legacy and
powermock-junit4. Ie project should only have to include a single powermock
jar file instead of multiple files. This will greatly simplify the use of
PowerMock for projects not using maven.

Original issue: http://code.google.com/p/powermock/issues/detail?id=1

PowerMock doesn't work correctly when using cobertura and Maven

From [email protected] on October 01, 2008 21:13:39

There seems to be a problem with cobertura, Maven and PowerMock.

For example adding cobertura to the DocumentationExamples project results
in the following error message (on Linux as well after configuring surefire
with cobertura.use.java.nio to false):

Cobertura: Loaded information on 5 classes.
Cobertura: Coverage data file
/home/johan/devtools/java/projects/powermock/examples/DocumentationExamples/target/cobertura/cobertura.ser
either does not exist or is not readable. Creating a new data file.
Cobertura: Error reading file
/home/johan/devtools/java/projects/powermock/examples/DocumentationExamples/target/cobertura/cobertura.ser:
null
Cobertura: Saved information on 1 classes.
Cobertura: Error reading file
/home/johan/devtools/java/projects/powermock/examples/DocumentationExamples/target/cobertura/cobertura.ser:
null
Cobertura: Coverage data file
/home/johan/devtools/java/projects/powermock/examples/DocumentationExamples/target/cobertura/cobertura.ser
either does not exist or is not readable. Creating a new data file.
Cobertura: Saved information on 5 classes.
Cobertura: Saved information on 1 classes.
[INFO] [cobertura:cobertura]
[INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura: Loaded information on 1 classes.
[cobertura] INFO [main]
net.sourceforge.cobertura.reporting.html.HTMLReport - Data file does not
contain instrumentation information for the file
powermock/examples/staticmocking/ServiceRegistrator.java. Ensure this
class was instrumented, and this data file contains the instrumentation
information.
Report time: 119ms

We need to address this if possible.

Original issue: http://code.google.com/p/powermock/issues/detail?id=21

Support recursive partial mocking

It would be cool to support "recursive partial mocking".

Imagine this:

void addFolderToLogPaths(final File logFolder, final List<LogFile> logFileList,
        final Collection<ITargetPersistenceUnit> persistentUnits) {
        if (!logFolder.isDirectory()) {
            throw new IllegalArgumentException("logPath is not a directory.");
        }

        final File[] allLogFiles = logFolder.listFiles();
        for (File fileOrDirectory : allLogFiles) {
            if (fileOrDirectory.isDirectory()) {
                addFolderToLogPaths(fileOrDirectory, logFileList,
persistentUnits);
            } else {
                logFileList.add(new
LogFile(getRelativeLogPath(fileOrDirectory), fileOrDirectory.lastModified(),
                    isFileReplayable(persistentUnits, fileOrDirectory)));
            }
        }
    }

We could implement so that one call to addFolderToLogPaths (the actual test
invocation) passes the MockGateway but sequential invocations should be
mocked.

Matchers doesn't work for arguments with expectPrivate

From [email protected] on September 09, 2008 16:58:10

This doesn't work:
expectPrivate(tested, getNewStringBuilderMethodName,
aryEq(message)).andReturn(expected);

It will produce:
java.lang.NullPointerException
at org.powermock.Whitebox.findMethodOrThrowException(Whitebox.java:364)
at org.powermock.PowerMock.expectPrivate(PowerMock.java:714)
at
se.myapp.service.model.LineSplitDataPackageWriterTest.testWrite_singleMessageWithNewLine(LineSplitDataPackageWriterTest.java:93)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:162)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:119)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:112)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:110)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:74)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:43)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

Original issue: http://code.google.com/p/powermock/issues/detail?id=5

createPartialMock should support private constructors with no arguments

From [email protected] on October 24, 2008 14:56:14

E.g. MyClass myClassMock = PowerMock.createPartialMock(MyClass.class, new
String[]{"loadMyClassDLL"}, null);

For ctor:
private MyClass() {
this.initialized = false;
this.connectedDUTs = new HashSet();
}

Generates the following error:
java.lang.NullPointerException
at org.powermock.Whitebox.getArgumentsAsString(Whitebox.java:526)
at
org.powermock.Whitebox.throwExceptionIfConstructorWasNotFound(Whitebox.java:512)
at
org.powermock.Whitebox.findConstructorOrThrowException(Whitebox.java:499)
at org.powermock.PowerMock.createPartialMock(PowerMock.java:636)
at
se.ericsson.eab.sdk.jMyClasswrapper.MyClassTest.connectToDUTFail(MyClassTest.java:358)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at

Original issue: http://code.google.com/p/powermock/issues/detail?id=37

invokeMethod throws NPE when an argument is null when the method cannot be found

From [email protected] on October 27, 2008 14:18:47

java.lang.NullPointerException
at org.powermock.Whitebox.getArgumentsAsString(Whitebox.java:529)
at org.powermock.Whitebox.throwExceptionIfMethodWasNotFound(Whitebox.java:508)
at org.powermock.Whitebox.findMethodOrThrowException(Whitebox.java:425)
at org.powermock.Whitebox.doInvokeMethod(Whitebox.java:341)
at org.powermock.Whitebox.invokeMethod(Whitebox.java:277)

Original issue: http://code.google.com/p/powermock/issues/detail?id=44

Investigate if we should byte-code manipulate an entire hierarchy

From [email protected] on October 29, 2008 12:34:50

Let's say we have a class called A which extends B. Suppose B has a
protected method called "myMethod" and we wish to create a partial mock of
A where only this method is mocked. Now we need to do both
@PrepareForTest({A.class, B.class}) which is non intuitive, perhaps we
should implicitly load B with the MockClassloader when doing
@PrepareForTest(A.class)?

Original issue: http://code.google.com/p/powermock/issues/detail?id=50

You shouldn't need to add all classes in a heirarchy when suppression constructors

From [email protected] on October 12, 2008 21:38:41

When using suppressConstructorHeirachy you should be able to do:

@PrepareForTest( SuppressConstructorHierarchyChild.class )
@RunWith(PowerMockRunner.class)
public class SuppressConstructorHierarchyDemoTest {
@test
public void testSuppressConstructor() throws Exception {

suppressConstructorCodeHierarchy(SuppressConstructorHierarchyChild.class);
}
..
}

instead of
@PrepareForTest( { SuppressConstructorHierarchyChild.class,
SuppressConstructorHierarchyParent.class,
SuppressConstructorHeirarchyEvilGrandParent.class })
@RunWith(PowerMockRunner.class)
public class SuppressConstructorHierarchyDemoTest {
..
}

Original issue: http://code.google.com/p/powermock/issues/detail?id=24

findConstructorOrThrowException and findMethodOrThrowException have critical bugs

From [email protected] on October 24, 2008 11:36:20

findConstructorOrThrowException in Whitebox have two critical bugs which
effects other parts of PowerMock (for example createPartialMock).
1:
if (!paramTypes[i].equals(arguments[i].getClass())) {
wrappedConstructorFound = false;
break;
}
Solution: arguments[i].getClass() must be changed to
getUnmockedType(arguments[i].getClass())

2:
The findPrimitiveMethodOrConstructor should be renamed to
hasWrapperArguments(return value must change from true to false)
If a primitive constructor is found parameter checking must take place!!!
This doesn't happen today!!

Original issue: http://code.google.com/p/powermock/issues/detail?id=34

createPartialMock no longer works as expected.

From [email protected] on October 24, 2008 09:26:51

Because we're adding a defer constructor in each class this will have
implications when creating partial mocks if there's only one constructor in
the class. I.e.

tested = createPartialMock(LineSplitDataPackageWriter.class, new String[] {
""}, mDataWriterMock);

java.lang.RuntimeException: Several matching constructors found, please
specify the argument parameter types so that PowerMock can determine which
method you're refering to.
Matching constructors in class se.myapp.LineSplitDataPackageWriter were:
se.myapp.service.model.LineSplitDataPackageWriter(
org.powermock.core.classloader.annotations.internal.IndicateReloadClass.class )
se.myapp.service.model.LineSplitDataPackageWriter(
se.myapp.IDataPackageWriter.class )

Original issue: http://code.google.com/p/powermock/issues/detail?id=33

expectNew(..).andThrow(..) no longer works with checked exceptions.

From [email protected] on October 01, 2008 10:34:29

For some reason it seems like the NewInvocationControl has been reverted
and doesn't support checked exceptions anymore.

NewInvocationControl should probably contain the method
public T createInstance() throws Exception;

Otherwise we'll run into:
java.lang.IllegalArgumentException: last method called on mock cannot throw
java.io.IOException
at org.easymock.internal.MocksControl.andThrow(MocksControl.java:110)
atse.myapp.TargetPersistenceManagerTest.testTargetConnect_failsToCreateFileName(TargetPersistenceManagerTest.java:418)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:162)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:119)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:112)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:110)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:74)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:43)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

It doesn't seem like the ExpectNewDemoTest#testNewWithCheckedException test
case tests for checked exceptions at all!!!

Original issue: http://code.google.com/p/powermock/issues/detail?id=18

ExpectNew doesn't work properly when throwing exceptions!

From [email protected] on September 08, 2008 09:56:10

Method looks like:
private Target createDomainTarget(ITarget target, boolean connecting) {
Target domainTarget = null;
try {
domainTarget = new Target(getTargetName(target, connecting),
target.getId());
} catch (MyException e) {
log.warn("Failed to get the target data from service");
domainTarget = new Target("Unknown", -1);
}
return domainTarget;
}

test looks like:

expectNew(Target.class).andThrow(new MyException("error!"));

    final String getTargetNameMethodName = "getTargetName";
    tested =
        mockMethod(ServiceTracker.class, new String[] {
            getTargetNameMethodName}, mServiceMock,

mAutoOpenDataStreamServiceMock,
mDataProviderAddedOrRemovedNotifierMock,
mTargetAddedOrRemovedNotifierMock);

    final boolean connecting = true;
    final String expectedTargetName = "Unknown";
    final int expectedId = -1;

    expectPrivate(tested, getTargetNameMethodName, mTargetMock1,

connecting).andReturn("A name");
expect(mTargetMock1.getId()).andReturn(2);

    replayAll();

    Target actual = (Target) Whitebox.invokeMethod(tested,

"createDomainTarget", new Class<?>[] {
ITarget.class, boolean.class}, mTargetMock1, connecting);

    verifyAll();

    assertEquals(expectedTargetName, actual.getName());
    assertEquals(expectedId, actual.getId());

Causes error stack:
java.lang.NullPointerException
at
se.ericsson.eab.sdk.logcoordinator.service.DebugMuxServiceTrackerTest.testCreateDomainTarget_ITarget_fails(DebugMuxServiceTrackerTest.java:545)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:162)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:119)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:112)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:110)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:74)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:43)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

The problem is that when invoking new Target(..) the exception doesn't seem
to be thrown or at least the execution is not reflected in the code, i.e.
log.warn(..) etc is never called. A new target is never created though.

Original issue: http://code.google.com/p/powermock/issues/detail?id=3

verify/replay doesn't work properly when mixing classes and instances

From [email protected] on September 09, 2008 15:43:12

verify calls verifyClass which clears the state! We need to refactor
verifyClass to a new private method that doesn't clear state.
verify(object...) and verifyClass should call this new method (the old
verifyClass should clear state though).

This happens when you do PowerMock.verify(MyClass.class, myInstance,
myInstance2); Before myInstance has been verified the PowerMock state has
been cleared.

Original issue: http://code.google.com/p/powermock/issues/detail?id=4

We need a better error message when expectNew fails due to too many calls to new.

From [email protected] on September 11, 2008 10:59:31

If we do expectNew(MyClass.class) once but it's called twice we should get
a more descriptive error message than the following:

java.lang.RuntimeException: java.lang.AssertionError:
Unexpected method call createInstance():
createInstance(): expected: 1, actual: 1 (+1)
at org.powermock.Whitebox.performMethodInvocation(Whitebox.java:788)
at org.powermock.Whitebox.invokeMethod(Whitebox.java:268)
at se.myapp.MyTest.testCreateDomainTarget(MyTest.java:577)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

We could perhaps catch the AssertionError in MockGateway line 117 ( return
newInvocationControl.createInstance()) and throw another AssertionError
with a better description instead.

Original issue: http://code.google.com/p/powermock/issues/detail?id=10

Only mock specific calls to new

Let's say you have a method like this:

private Target createTarget(ITarget target) {
        Target domainTarget = null;
        try {
            domainTarget = new Target(getTargetName(target), target.getId());
        } catch (CreationException e) {
            domainTarget = new Target("Unknown", -1);
        }
        return domainTarget;
}

In one case here we'd like to mock the first instance creation of Target
and throw a CreationException but we'd like to make sure that a new Target
has been created with parameters "Unknown" and -1. This is not possible today.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.