Code Monkey home page Code Monkey logo

mockito's Introduction

Mockito

Most popular mocking framework for Java

CI Coverage Status MIT License

Release Notes Maven Central Javadoc

Current version is 5.x

Still on Mockito 1.x? See what's new in Mockito 2! Mockito 3 does not introduce any breaking API changes, but now requires Java 8 over Java 6 for Mockito 2. Mockito 4 removes deprecated API. Mockito 5 switches the default mockmaker to mockito-inline, and now requires Java 11. Only one major version is supported at a time, and changes are not backported to older versions.

Mockito for enterprise

Available as part of the Tidelift Subscription.

The maintainers of org.mockito:mockito-core and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Development

Mockito publishes every change as a -SNAPSHOT version to a public Sonatype repository. Roughly once a month, we publish a new minor or patch version to Maven Central. For release automation we use Shipkit library (http://shipkit.org), Gradle Nexus Publish Plugin. Fully automated releases are awesome, and you should do that for your libraries, too! See the latest release notes and latest documentation. Docs in javadoc.io are available 24h after release. Read also about semantic versioning in Mockito.

Older 1.x and 2.x releases are available in Central Repository and javadoc.io (documentation).

More information

All you want to know about Mockito is hosted at The Mockito Site which is Open Source and likes pull requests, too.

Want to contribute? Take a look at the Contributing Guide.

Enjoy Mockito!

Need help?

How to develop Mockito?

To build locally:

 ./gradlew build

To develop in IntelliJ IDEA you can use built-in Gradle import wizard in IDEA. Alternatively generate the importable IDEA metadata files using:

 ./gradlew idea

Then, open the generated *.ipr file in IDEA.

How to release new version?

  1. Every change on the main development branch is released as -SNAPSHOT version to Sonatype snapshot repo at https://s01.oss.sonatype.org/content/repositories/snapshots/org/mockito/mockito-core.
  2. In order to release a non-snapshot version to Maven Central push an annotated tag, for example:
git tag -a -m "Release 3.4.5" v3.4.5
git push origin v3.4.5
  1. At the moment, you may not create releases from GitHub Web UI. Doing so will make the CI build fail because the CI creates the changelog and posts to GitHub releases. We'll support this in the future.

mockito's People

Contributors

andreastu avatar ascopes avatar bbankowski avatar big-andy-coates avatar bric3 avatar christianschwarz avatar continuous-delivery-drone avatar davidkarlsen avatar dawood-ibn-kareem avatar dependabot[bot] avatar epeee avatar iczechowski avatar lpandzic avatar lukasz-szewc avatar marchpig avatar marcingrzejszczak avatar marcphilipp avatar mockitoguy avatar moltmann avatar mureinik avatar pascalschumacher avatar pimterry avatar raphw avatar reta avatar scordio avatar shestee avatar shipkit-org avatar szpak avatar timvdlippe avatar twisterrob 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

mockito's Issues

New release

It would be really great if we could get out a new release of Mockito.

Getting an absolute count of calls to a mocked method

We can do this:

verify(mock1, times(3)).thisMethod();
verify(mock2, times(3)).thatMethod();

But we cannot do something like this, as far as I can see:

verifyEquals(times(mock1.thisMethod()), times(mock2.thatMethod()));

That is, I would like to verify that two mocked methods are called the same unspecified number of times. The number of calls made to a method appears to be already available, so this would be just querying the value directly, not indirectly via times(), atLeast(), etc.

I also posed this question to StackOverflow, and one answer, on using an Answer, seems good; perhaps a standard Answer implementation CountsCalls or similar should be the solution?

Spying and Verification Doesn't Work On Instances Created With Javassist

Spying on objects created using Javassist framework doesn't seem to work. Here is a simple test case that demonstrates the issue. Note that verification doesn't work at all. I'm not entirely sure what the issue is but I suspect it may have something to do with MockUtil.createMock(...) method and copying of fields. It seems odd to me that fields are being copied instead of having the mockito created spy instance subclassing and implementing all the interfaces of the instance being spyed on and delegating calls to the original instance.

import java.lang.reflect.Method;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

/**
 *
 * @author Sharmarke Aden
 */
public class JavassistMockitoSpyNGTest {

    User sut;

    @BeforeTest
    public void init() throws InstantiationException, IllegalAccessException {
        //let's create a proxy using javasist.
        ProxyFactory factory = new ProxyFactory();
        factory.setSuperclass(User.class);
        factory.setInterfaces(new Class[]{Principle.class});
        Class clazz = factory.createClass();
        //create a delegate instance
        User delegate = new User("username", "password");
        //create a method handler that delegates calls to the above delegate
        MethodHandler handler = new UserMethodHandler(delegate);
        //create a new instance and set its proxy method invocation hander
        this.sut = (User) clazz.newInstance();
        ((ProxyObject) sut).setHandler(handler);
    }

    @Test
    public void givenJavasistProxyInstanceMockitoShouldCreateSpy() {
        //make sure delegation works and we are getting expected values
        String username = sut.getUsername();
        assertThat(username).isEqualTo("username");

        String password = sut.getPassword();
        assertThat(password).isEqualTo("password");

        //now create a spy and try to verify 
        User spy = spy(sut);

        username = spy.getUsername();
        assertThat(username).isEqualTo("username");

        password = spy.getPassword();
        assertThat(password).isEqualTo("password");

        //works but should fail!
        verify(spy, times(2)).getUsername();
        //verification fails!
        verify(spy).getPassword();

    }

    public static class UserMethodHandler implements MethodHandler {

        private final User delegate;

        public UserMethodHandler(User delegate) {
            this.delegate = delegate;
        }

        @Override
        public Object invoke(Object self, Method overridden, Method forwarder, Object[] args) throws Throwable {
            return overridden.invoke(delegate, args);
        }

    }

    public static interface Principle {

        String getUsername();

    }

    public static class User implements Principle {

        private final String username;
        private final String password;

        public User() {
            this.username = null;
            this.password = null;
        }

        public User(String username, String password) {
            this.username = username;
            this.password = password;
        }

        @Override
        public String getUsername() {
            return username;
        }

        public String getPassword() {
            return password;
        }

    }
}

Concise way to collect multiple verify failures, ideally with JUnitCollector or derivative

If you are using more than one verify statement as test post-conditions, it would be nice to be able to collect each failure and continue with the remaining verify statements or asserts that follow. JUnit provides the ErrorCollector @rule to facilitate this kid of thing, but the current ErrorCollector API requires either

  • a Matcher and a value to compare
  • or a Callable

    The Mockito verify statements only return void, however, since they depend on throwing exceptions. I have not thought of an ideal, non-disruptive way to use JUnit's ErrorCollector to aggregate multiple Mockito verify failure

NullPointerException when using argThat() for long parameter in verify

A minimal code example:

  @Test
  public void shouldNotBeBroken() throws Exception {
    TakesALong takesALong = mock(TakesALong.class);

    verify(takesALong).call(argThat(CoreMatchers.equalTo(11L)));
  }

  static interface TakesALong {
    void call(long l);
  }

This leads to an NPE logged as happening at the 'verify' call, which made me think that the the result of verify(takesALong) was null, but it seems like the NPE has a somewhat incomplete stack trace. Variations that don't show this problem include:

  • changing the interface to take a Long instead of a long, or
  • using longThat(Matcher<Long>) instead of argThat()

If it is considered an error to use argThat where you're passing in a long, then I think at least there should be a better error message.

1.10 regression (StackOverflowError) with interface where generic type has itself as upper bound

Add this to GenericMetadataSupportTest:

    interface GenericsSelfReference<T extends GenericsSelfReference<T>> {
        T self();
    }

    @Test
    public void typeVariable_of_self_type() {
        GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class));

        assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class);
    }

It fails on master and 1.10.8 with this:

java.lang.StackOverflowError
    at sun.reflect.generics.reflectiveObjects.TypeVariableImpl.hashCode(TypeVariableImpl.java:201)
    at java.util.HashMap.hash(HashMap.java:338)
    at java.util.HashMap.get(HashMap.java:556)
    at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:193)
    at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)
    at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)

It worked on 1.9.5. May be caused by the changes in ab9e9f3 (cc @bric3).

(Also note that while the above interface looks strange, it is commonly used for builder hierarchies, where base class methods want to return this with a more specific type.)

Argument matcher anyXxx() (i.e. anyString(), anyList()) should not match nulls

This is a bug I'm seeing in 1.10.8 version (older version has the same issue - tested with 1.9.0).

Given:

Function<Object, Integer> function = Mockito.mock(Function.class);
when(function.apply(Mockito.anyString())).thenReturn(1);
Integer result = function.apply(2);

Expected behavior:

result == null;

Actual behavior:

result == 1;

Note that the function is called with an integer (not a string), and still the mocked function return the value which it should return only when a string is passed. The same works when using anyBoolean() or any other methof from any* family.

Allow instances of other classes in AdditionalAnswers.delegatesTo

We have AdditionalAnswers.delegatesTo, but if an object of the wrong type is passed we get a RuntimeException:

java.lang.IllegalArgumentException: object is not an instance of declaring class

If we allow any type as long as it has the needed methods of the same signature, then we can create fake objects like:

class FakeSession {
    Map<String, Object> map = new HashMap<>();

    public Object getAttribute(String key) {
        return map.get(key);
    }

    public void setAttribute(String key, Object value) {
        map.put(key, value);
    }
}

@Test
public void test() {
    HttpSession session = mock(HttpSession.class,
        AdditionalAnswers.delegatesTo(new FakeSession()));

    session.setAttribute("key", "value");

    assertEquals("value", session.getAttribute("key"));
}

This saves on implementing many methods that are not used in the test, and can be easier to write than adding separate Answers for each call. This can be used to create fakes for objects like SWT's StyledText which has a huge number of methods. Using a separate object instead of a subclass prevents code from accidentely calling the real object or requiring the real constructor to be called.

This is not type-safe but it doesn't seem any worse than the casting required in Answers, and the user will find out quickly if a required method doesn't exist by running the tests.

I propose to modify the implementation of ForwardsInvocations with something like:

public Object answer(InvocationOnMock invocation) throws Throwable {
    Method mockMethod = invocation.getMethod();

    if(mockMethod.getDeclaringClass().isAssignableFrom(delegatedObject.getClass())) {
        return mockMethod.invoke(delegatedObject, invocation.getArguments());
    } else {
        Method delegateMethod = delegatedObject.getClass().getMethod(
            mockMethod.getName(), mockMethod.getParameterTypes());
        return delegateMethod.invoke(delegatedObject, invocation.getArguments());
    }
}

Consume new cglib and asm versions

I'd like Mockito to consume a newer cglib and asm version to address issues with class generation and class loaders in OSGi environments and for Java 8 support. It seems that Mockito needs to consume at least ASM 5 and a new - yet to be released - build for cglib.

I've initiated discussion at cglib in order to get a new cglib release.
cglib/cglib#20

I've prepared pull requests #83 and #81 on the Mockito site in order to start preparing for consuming new bits from asm and cglib.

Allow convenient spying on abstract classes

I posted this in GoogleCode and was asked to submit in github.

Mockito is easy to use when the test needs to provide canned values for a certain method.

But it gets harder when a canned value isn't sufficient.

Example 1: Fake with trivial Logic
interface UserAccount {
  List<String> getEmails();
  void addEmail(String email);
  // 12 other methods ...
}

When mocking such domain entity object, it's tedious to manually program getEmails()/addEmail() with when().thenReturn() and to make sure the two methods are logically consistent, that is, getEmails() returns all emails added.

Example 2: callback-style API
interface AccountService {
  void getAccount(String id, AsyncCallback<UserAccount> callback);
}

Stubbing AccountService isn't easy. It'd require use of Answer, and the Answer API isn't statically type safe:

when(service.getAccount(eq(id), any(AsyncCallback.class)).thenAnswer(new Answer<Void>() {
  AsyncCallback<UserAccount> callback = (AsyncCallback<UserAccount>) getArguments()[1];
  ...
});
Example 3: Uninteresting parameters
interface AccountRpcService {
  FutureAccount getAccount(RpcContext context, String id);
}

None of the tests care about the context object. It's an uninteresting parameter imposed by the framework.

If AccountRpcService were directly mocked, all tests would have to use isA() to repetitively mention this uninteresting parameter, like this:

when(service.getAccount(isA(RpcContext.class), eq("id")).thenReturn(...);

And all other parameters are required to be wrapped in eq().

Proposal

I propose adding support for abstract classes to mockito to make it easier to deal with tests like above:

For example 1
abstract class FakeUserAccount implements UserAccount {
  private final List<String> emails = new ArrayList<>();

  @Override public void addEmail(String email) {
    emails.add(email);
  }
  @Override List<String> getEmails() {
    return ImmutableList.copyOf(emails);
  }
}

@Fake private FakeUserAccount userAccount; // Mockito instantiates abstract class.
For example 2
abstract class MockAccountService implements AccountService {
  @Override public void getAccount(String id, AsyncCallback<UserAccount> callback) {
    callback.onSuccess(getAccount(id));
  }
  abstract UserAccount getAccount(String id);
}

@Fake private MockAccountService service;

...

when(service.getAccount("id")).thenReturn(account);
For example 3
abstract class MockAccountRpcService implements AccountRpcService {
  @Override Future<Account> getAccount(RpcContext context, String id) {
    checkNotNull(context);  // Common sanity test. Don't have to repeat it in tests.
    return getAccount(id);
  }

  abstract Future<Account> getAccount(String id);
}

@Fake private MockAccountRpcService service;

when(service.getAccount("id")).thenReturn(...);

My work place internally implemented a default Answer to support abstract classes. We found that the support of abstract classes helps us to avoid overusing mocks when we should be using fakes. And in situations like above we get cleaner test code.

But because it's not integrated in the core Mockito, there are gotchas with our implementation (like, you can't have private/final methods in your fake).

If the idea sounds okay to give a try, I'll volunteer to submit a patch.

Thanks!

Release Mockito 2.0

Incompatible changes:

  • stop producing mockito-all #153
  • stop depending on hamcrest internally #154
  • use newer hamcrest #232
  • make the anyXxx and any(Xxx) matchers intuitive #134, #194
  • fix the site links
  • push cglib mockmaker to a separate jar #248
  • stop using ant for producing OSGi bundles. No more ant in the build #249
  • remove jars from source distribution #250
  • perhaps introduce is() matcher #246
  • richer and smarter stubbing #303
  • support java8 features for capturing arguments and matchers
  • make the JUnitRule and the runner verbose
  • ensure release notes can be neatly generated for the RC #582

Possibly compatible (and hence, could be released pre-2.0 if needed)

  • drop deprecated code
  • unincubate API
  • drop serialVersionUID

possible NPE exception when class cannot be mocked via PowerMockito

In version 1.10.5, the catch block needs to guard against a null proxyInstance:

java.lang.NullPointerException
at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:65)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:60)
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:143)
at com.seagullsw.appinterface.server.osgi.JCicsOsgiTestCase.executeOsgiRequest(JCicsOsgiTestCase.java:167)
at com.seagullsw.appinterface.server.osgi.JCicsOsgiTestCase.executeOsgiRequest(JCicsOsgiTestCase.java:122)
at com.seagullsw.appinterface.server.osgi.JCicsOsgiTestCase.checkFunctionReturnString(JCicsOsgiTestCase.java:99)
at com.seagullsw.appinterface.server.osgi.JCicsOsgiTestCase.testJcicsOsgiRoundtrip(JCicsOsgiTestCase.java:230)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

java.lang.NoClassDefFoundError: org.mockito.internal.runners.RunnerImpl on ART on L Preview on Android

Mockito doesn't seem to work on ART ( on L preview or Kitkat )

Also, see here:
http://stackoverflow.com/questions/20514588/instrumentation-result-shortmsg-java-lang-noclassdeffounderror-running-android

and here:

https://code.google.com/p/android-developer-preview/issues/detail?id=1081

    java.lang.NoClassDefFoundError: org.mockito.internal.runners.RunnerImpl
            at java.lang.Class.classForName(Native Method)
            at java.lang.Class.forName(Class.java:308)
            at android.test.ClassPathPackageInfoSource.createPackageInfo(ClassPathPackageInfoSource.java:88)
            at android.test.ClassPathPackageInfoSource.access$000(ClassPathPackageInfoSource.java:39)
            at android.test.ClassPathPackageInfoSource$1.load(ClassPathPackageInfoSource.java:50)
            at android.test.ClassPathPackageInfoSource$1.load(ClassPathPackageInfoSource.java:47)
            at android.test.SimpleCache.get(SimpleCache.java:31)
            at android.test.ClassPathPackageInfoSource.getPackageInfo(ClassPathPackageInfoSource.java:72)
            at android.test.ClassPathPackageInfo.getSubpackages(ClassPathPackageInfo.java:48)
            at android.test.ClassPathPackageInfo.addTopLevelClassesTo(ClassPathPackageInfo.java:61)
            at android.test.ClassPathPackageInfo.getTopLevelClassesRecursive(ClassPathPackageInfo.java:55)
            at android.test.suitebuilder.TestGrouping.testCaseClassesInPackage(TestGrouping.java:156)
            at android.test.suitebuilder.TestGrouping.addPackagesRecursive(TestGrouping.java:117)
            at android.test.suitebuilder.TestSuiteBuilder.includePackages(TestSuiteBuilder.java:100)
            at android.test.InstrumentationTestRunner.onCreate(InstrumentationTestRunner.java:367)
08-11 15:14:57.406    2313-2313/? W/ClassPathPackageInfoSource๏น• Cannot load class. Make sure it is in your apk. Class name: 'org.mockito.cglib.transform.AbstractTransformTask'. Message: org.mockito.cglib.transform.AbstractTransformTask
    java.lang.ClassNotFoundException: org.mockito.cglib.transform.AbstractTransformTask
            at java.lang.Class.classForName(Native Method)
            at java.lang.Class.forName(Class.java:308)
            at android.test.ClassPathPackageInfoSource.createPackageInfo(ClassPathPackageInfoSource.java:88)
            at android.test.ClassPathPackageInfoSource.access$000(ClassPathPackageInfoSource.java:39)
            at android.test.ClassPathPackageInfoSource$1.load(ClassPathPackageInfoSource.java:50)
            at android.test.ClassPathPackageInfoSource$1.load(ClassPathPackageInfoSource.java:47)
            at android.test.SimpleCache.get(SimpleCache.java:31)
            at android.test.ClassPathPackageInfoSource.getPackageInfo(ClassPathPackageInfoSource.java:72)
            at android.test.ClassPathPackageInfo.getSubpackages(ClassPathPackageInfo.java:48)
            at android.test.ClassPathPackageInfo.addTopLevelClassesTo(ClassPathPackageInfo.java:61)
            at android.test.ClassPathPackageInfo.getTopLevelClassesRecursive(ClassPathPackageInfo.java:55)
            at android.test.suitebuilder.TestGrouping.testCaseClassesInPackage(TestGrouping.java:156)
            at android.test.suitebuilder.TestGrouping.addPackagesRecursive(TestGrouping.java:117)
            at android.test.suitebuilder.TestSuiteBuilder.includePackages(TestSuiteBuilder.java:100)
            at android.test.InstrumentationTestRunner.onCreate(InstrumentationTestRunner.java:367)
            at com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner.onCreate(GoogleInstrumentationTestRunner.java:114)
            at com........TestRunner.onCreate(.....InstrumentationTestRunner.java:71)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4388)
            at android.app.ActivityThread.access$1500(ActivityThread.java:143)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5070)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:836)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:631)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "org.mockito.cglib.transform.AbstractTransformTask" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/data/app/.....debug.test-1.apk", zip file "/data/app/.....debug-1.apk"],nativeLibraryDirectories=[/data/app-lib/...debug.test-1, /data/app-lib/....debug-1, /vendor/lib, /system/lib]]
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
ย ย ย ย ย ย ย ย ย ย ย ย at java.lang.Class.classForName(Native Method)
ย ย ย ย ย ย ย ย ย ย ย ย at java.lang.Class.forName(Class.java:308)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.ClassPathPackageInfoSource.createPackageInfo(ClassPathPackageInfoSource.java:88)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.ClassPathPackageInfoSource.access$000(ClassPathPackageInfoSource.java:39)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.ClassPathPackageInfoSource$1.load(ClassPathPackageInfoSource.java:50)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.ClassPathPackageInfoSource$1.load(ClassPathPackageInfoSource.java:47)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.SimpleCache.get(SimpleCache.java:31)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.ClassPathPackageInfoSource.getPackageInfo(ClassPathPackageInfoSource.java:72)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.ClassPathPackageInfo.getSubpackages(ClassPathPackageInfo.java:48)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.ClassPathPackageInfo.addTopLevelClassesTo(ClassPathPackageInfo.java:61)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.ClassPathPackageInfo.getTopLevelClassesRecursive(ClassPathPackageInfo.java:55)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.suitebuilder.TestGrouping.testCaseClassesInPackage(TestGrouping.java:156)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.suitebuilder.TestGrouping.addPackagesRecursive(TestGrouping.java:117)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.suitebuilder.TestSuiteBuilder.includePackages(TestSuiteBuilder.java:100)
ย ย ย ย ย ย ย ย ย ย ย ย at android.test.InstrumentationTestRunner.onCreate(InstrumentationTestRunner.java:367)
ย ย ย ย ย ย ย ย ย ย ย ย at com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner.onCreate(GoogleInstrumentationTestRunner.java:114)
ย ย ย ย ย ย ย ย ย ย ย ย at com............TestRunner.onCreate(.....InstrumentationTestRunner.java:71)
ย ย ย ย ย ย ย ย ย ย ย ย at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4388)
ย ย ย ย ย ย ย ย ย ย ย ย at android.app.ActivityThread.access$1500(ActivityThread.java:143)
ย ย ย ย ย ย ย ย ย ย ย ย at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
ย ย ย ย ย ย ย ย ย ย ย ย at android.os.Handler.dispatchMessage(Handler.java:102)
ย ย ย ย ย ย ย ย ย ย ย ย at android.os.Looper.loop(Looper.java:135)
ย ย ย ย ย ย ย ย ย ย ย ย at android.app.ActivityThread.main(ActivityThread.java:5070)
ย ย ย ย ย ย ย ย ย ย ย ย at java.lang.reflect.Method.invoke(Native Method)
ย ย ย ย ย ย ย ย ย ย ย ย at java.lang.reflect.Method.invoke(Method.java:372)
ย ย ย ย ย ย ย ย ย ย ย ย at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:836)
ย ย ย ย ย ย ย ย ย ย ย ย at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:631)
    Suppressed: java.lang.NoClassDefFoundError: org.mockito.cglib.transform.AbstractProcessTask
            at dalvik.system.DexFile.defineClassNative(Native Method)
            at dalvik.system.DexFile.defineClass(DexFile.java:222)
            at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:215)
            at dalvik.system.DexPathList.findClass(DexPathList.java:321)
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:54)
            ... 29 more
    Suppressed: java.lang.ClassNotFoundException: org.mockito.cglib.transform.AbstractTransformTask
            at java.lang.Class.classForName(Native Method)
            at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
            at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            ... 28 more
     Caused by: java.lang.NoClassDefFoundError: Class "Lorg/mockito/cglib/transform/AbstractTransformTask;" not found
            ... 32 more
111

Default answer to fail on an unstubbed method invocation

Sometimes it is usefull to ensure that a test uses only mocked method calls. The test should fail on the invocation of an unmocked method call. Therefore it would be usefull to have an additional Answer in Answers which throws an exception if a unmocked method is called.

When trying to mock a non final class, get java.lang.NoClassDefFoundError: com.ibm.ecm.util.DocumentContent

Hello everyone,

When I try to mock a class (with annotation or via code), I get the following exception. It makes sense there is missing dependencies since it is a plug-in running inside an application on a JEE server. However I thought for a mock deep dependencies wouldn't be an issue. I have a lot of other classes like that, not running by their self but mocked fine. Is their something I doing wrong, or it is just not possible to mock this class. I can't mock any interface because this class does not implement any.

Thanks a lot!

Mockito Version: 1.9.5
JRE: 7 IBM 32bits
IDE: Eclipse Luna (4.4.0)
JUnit: 4.11.0

Failing code:
@Mock PluginServiceCallbacks callbacks;
or
callbacks = Mockito.mock(PluginServiceCallbacks.class);

Stack trace:

java.lang.NoClassDefFoundError: com.ibm.ecm.util.DocumentContent
    at java.lang.J9VMInternals.verifyImpl(Native Method)
    at java.lang.J9VMInternals.verify(J9VMInternals.java:73)
    at java.lang.J9VMInternals.prepare(J9VMInternals.java:459)
    at java.lang.Class.getDeclaredConstructors(Class.java:535)
    at org.mockito.internal.creation.jmock.ClassImposterizer.setConstructorsAccessible(ClassImposterizer.java:75)
    at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:70)
    at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)
    at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:60)
    at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:203)
    at org.powermock.api.extension.listener.AnnotationEnabler.standardInject(AnnotationEnabler.java:106)
    at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:54)
    at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:90)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:292)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: com.ibm.ecm.util.DocumentContent
    at java.net.URLClassLoader.findClass(URLClassLoader.java:434)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:677)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:358)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:643)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:178)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:68)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:643)
    ... 33 more

Expose 'internal' classes so Powermock-osgi can be incorporated without special builds of Mockito

I'm trying to get Powermock and mockito into the JBoss Tooling Target plaform and is being placed on hold (https://issues.jboss.org/browse/JBIDE-18053). This thread (https://code.google.com/p/powermock/issues/detail?id=204) mentions there are some dependencies on internal classes. I would like to expose those internals such that mockito and powermock can be pulled into the eclipse repos as part of the target platform. I'm available to help if someone can point me where to start

Continuous deployment should not release new version if binaries are equal

Continuous deployment should not release new version if binaries are equal. Sometimes we check-in code that does not require new version (for example, changes to README.md, itp). We should add some logic that prevents releasing a brand new version if the current binaries are the same as previously released.

Removing mockingDetails API from Mockito

After some exchange with other member of the community, code such as

Mockito.mockingDetails(someObject).isMock();
Mockito.mockingDetails(someObject).isSpy();

It looks wrong ; Mockito is the entry point for user friendly usage from within the test. Inspecting mocks looks wrong when it's a normal user.

However I know framework developers may need to inspect mocks. Let's keep the MockingDetails type but instantiate it from another static factory method.

The drawback is the removal of this API for current users. Maybe we can mark Mockito.mockingDetails(..) deprecated in 1.9.x and remove it in 2.0.0

NullPointerException when stubbing a class in Groovy 2.3.6

Setup
Groovy 2.3.6
Mockito 1.9.5
JDK 8

Given a test written in Groovy

package com.ofg.twitter.controller.place.extractor

import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock

import static org.mockito.Mockito.when

@RunWith(MockitoJUnitRunner)
class MockitoTest {

    private static final String PAID = 'PAID'

    @Mock PaymentOrderStatusChecker checkerMock

    @Test
    void testSth() {
        String paymentOrderId = "examplePaymentOrderIdUsedInTests1"

        when(checkerMock.checkStatus(paymentOrderId)).thenReturn(PAID)

        assert checkerMock.checkStatus(paymentOrderId) == PAID
    }
}

class PaymentOrderStatusChecker {
    String checkStatus(String status) {
        return ''
    }
}

When I exeucte the code

Then I receive

java.lang.NullPointerException
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at com.ofg.twitter.controller.place.extractor.MockitoTest.testSth(MockitoTest.groovy:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Mockito can't spy on object loaded in parent classloader

I have encountered issue with Mockito (I have tested this on 1.10.14) and usage of different classloaders - running tests in SBT 0,13.

I have got empty class TestClass and following test:

    @Test
    public void runTest() {
        Mockito.spy(new TestClass(){

        });
    }

This test fails with following:

Caused by: org.mockito.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
[error]     at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:238)
[error]     at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
[error]     at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
[error]     at org.mockito.internal.creation.cglib.ClassImposterizer.createProxyClass(ClassImposterizer.java:123)
[error]     at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:57)
[error]     at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
[error]     at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
[error]     at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
[error]     at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
[error]     at org.mockito.Mockito.spy(Mockito.java:1367)
[error]     ... 56 more
[error] Caused by: java.lang.reflect.InvocationTargetException
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
[error]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[error]     at java.lang.reflect.Method.invoke(Method.java:606)
[error]     at org.mockito.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:385)
[error]     at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:220)
[error]     ... 65 more
[error] Caused by: java.lang.IllegalAccessError: class TestMock$1$$EnhancerByMockitoWithCGLIB$$7c797c20 cannot access its superclass TestMock$1
[error]     at java.lang.ClassLoader.defineClass1(Native Method)
[error]     at java.lang.ClassLoader.defineClass(ClassLoader.java:800)

Looks like there is class loader issue - in sbt, the default classloader is the one for the sbt launcher, but you are "run" in a sub classloader.

Following calls give different result: Thread.currentThread().getContextClassLoader().getClass(); and TestClass.class.getClassLoader().getClass();
The second one is the parent of the first one.

Of course there is no issue running this piece of code in IDE, but in my opinion this is Mockito's problem, something which could be improved.

Is it possible to have this fixed in Mockito? I would say so because changing current classloader to the one used to load the class solves the issue.

Deep stubbing with generic responses in the call chain is not working

Deep stubbing will throw an Exception if multiple generics occur in the call chain. For instance, consider having a mock myMock1 that provides a function that returns a generic T. If T also has a function that returns a generic, an Exception with the message "Raw extraction not supported for : 'null'" will be thrown.

As an example the following test will throw an Exception:

public class MockitoGenericsDeepStubTest {

    @Test
    public void discoverDeepMockingOfGenerics() {
        MyClass1 myMock1 = mock(MyClass1.class, RETURNS_DEEP_STUBS);

        when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World.");
    }

    public static interface MyClass1 <MC2 extends MyClass2> {
        public MC2 getNested();
    }

    public static interface MyClass2<MC3 extends MyClass3> {
        public MC3 getNested();
    }

    public static interface MyClass3 {
        public String returnSomething();
    }
}

You can make this test run if you step into the class ReturnsDeepStubs and change the method withSettingsUsing to return MockSettings with ReturnsDeepStubs instead of ReturnsDeepStubsSerializationFallback as default answer:

private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) {
    MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ?
            withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces())
            : withSettings();

    return propagateSerializationSettings(mockSettings, parentMockSettings)
            .defaultAnswer(this);
}

However, this breaks other tests and features.

I think, the issue is that further generics are not possible to be mocked by ReturnsDeepStubsSerializationFallback since the GenericMetadataSupport is "closed" at this point.

Thanks and kind regards
Tobias

Improve automated release notes look

  • Let's ditch the top level "Improvements:" element.
  • Let's remove the 'Other' label and put unlabelled elements under 'Enhancements'

Anyone interested to pick this up? :)

Mockito won't build on a Windows machine

Executing gradlew pTLM results in the following:

(...)
:buildSrc:build UP-TO-DATE
Version: 1.10.45-dev
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:allJar FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':allJar'.
> A problem occurred starting process 'command 'ant''

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 24.438 secs

The stacktrace ends with this:

Caused by: org.gradle.process.internal.ExecException: A problem occurred starting process 'command 'ant''
        at org.gradle.process.internal.DefaultExecHandle.setEndStateInfo(DefaultExecHandle.java:196)
        at org.gradle.process.internal.DefaultExecHandle.failed(DefaultExecHandle.java:325)
        at org.gradle.process.internal.ExecHandleRunner.run(ExecHandleRunner.java:83)
        ... 1 more
Caused by: net.rubygrapefruit.platform.NativeException: Could not start 'ant'
        at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:27)
        at net.rubygrapefruit.platform.internal.WindowsProcessLauncher.start(WindowsProcessLauncher.java:22)
        at net.rubygrapefruit.platform.internal.WrapperProcessLauncher.start(WrapperProcessLauncher.java:36)
        at org.gradle.process.internal.ExecHandleRunner.run(ExecHandleRunner.java:65)
        ... 1 more
Caused by: java.io.IOException: Cannot run program "ant" (in directory "C:\projects\mockito\src\mockito"): CreateProcess
 error=2, The system cannot find the file specified
        at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:25)
        ... 4 more
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
        ... 5 more

Not a big deal, but caused some trouble.

Defining a new mocked method invokes previously defined one

For instance, the following test fails with java.lang.RuntimeException: Init mock exception:

interface Mockable {
    public int method(int param);
}

public class MockitoTest {
    private Mockable myMock;

    @Before
    public void init() {
        myMock = Mockito.mock(Mockable.class);
        when(myMock.method(anyInt())).thenThrow(new RuntimeException("Init mock"));
    }

    @Test
    public void test() {
        when(myMock.method(eq(1))).thenReturn(1);
    }
}

So, the parameter in when statement in test actualy invoked previously defined mock method from init.

Consequently, this means that I can't define more abstract mock in my init method and override it, if necessary, in some of my tests.

RETURNS_DEEP_STUBS automatically tries to create serializable mocks

I am just migrating from mockito 1.9.5 to 1.10.5

The following code runs fine with version 1.9.5. but breaks now:

  @Test
  public void test() {
    ToBeMocked mock = mock(ToBeMocked.class, RETURNS_DEEP_STUBS);
    assertThat(mock.getSomething()).isNotNull();
  }

  public static class ToBeMocked {

    NotSerializableReturnValue field1;

    public ToBeMocked(NotSerializableReturnValue field1) {
      this.field1 = field1;
    }

    public NotSerializableReturnValue getSomething() {
      return field1;
    }
  }

  public static class NotSerializableReturnValue {

    String field1 = "";

    public NotSerializableReturnValue(String field1) {
      this.field1 = field1;
    }

    public String getSomething2() {
      return field1;
    }
  }

org.mockito.exceptions.base.MockitoException:
You are using the setting 'withSettings().serializable()' however the type you are trying to mock 'NotSerializableReturnValue'
do not implement Serializable AND do not have a no-arg constructor.

Flickering test

Discussion started here - https://groups.google.com/forum/#!topic/mockito-dev/lDbmq9X622Y

Just as a reminder:

Hey

Build failed due to a fluke I think:

org.mockito.verification.TimeoutTest >
should_try_to_verify_correct_number_of_times FAILED

org.mockito.exceptions.verification.TooManyActualInvocations at 

TimeoutTest.java:71

The test seems to be flaky?

If someone can push DUMMY_COMMIT.txt to force the build and make it
green again; and take a look into the test and make it more stable
that would be most awesome :)

Cheers!

Szczepan Faber

Improve documentation

Documentation is missing many important features (or at least should introduce them in the main readme even they are somewhere described if you find):

For most I'd include the relevant import as well. I'd also put an example verify() with any() before even one verifying a specific object was called.

Clarify Spy vs Mock CALLS_REAL_METHODS

I'd suggest adding a comment or side note in [@InjectMocks](http://mockito.github.io/mockito/docs/current/org/mockito/InjectMocks.html) to explain that when you want to inject real instances (and not mocks) you have the choice (unless I'm mistaken) between [@Spy](http://mockito.github.io/mockito/docs/current/org/mockito/Spy.html) and [@Mock(answer = CALLS_REAL_METHODS)](http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html#CALLS_REAL_METHODS) but the former is preferable, because...

Add Matchers.any(Object) or Marchers.any(Type)

Matchers.any(Object) can receive any object, and via reflection, any() can figure out the right type (including generics). Ex.: any(new ImmutableSet<Foo>())

Or maybe have a Type class, something like guice's Key. Ex: any(new Key<ImmutableSet<Foo>>())

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.