Why is my Mockito-based unit test unable to run in Eclipse?

13,656

Solution 1

Make sure the unit-test classpath has the correct mockito. You can check this from the run dialog. Btw, Eclipse does not ship with mockito, so perhaps you are having two versions of it. Take a look at your maven dependency graph and search for duplicates.

Solution 2

I had the similar problem and I found that I had both "mockito-all 1.8.x" and "mockito-core 1.9.5" in my classpath. I was supposed to use only 1.9 but somehow eclipse was putting 1.8 before 1.9.5 in the classpath. I removed 1.8.x and it worked ;)

Share:
13,656
Coderer
Author by

Coderer

Updated on November 20, 2022

Comments

  • Coderer
    Coderer over 1 year

    I have a Maven-managed project that uses Mockito mocking in its unit tests. I can run all the tests within a Maven build, and they run without error (and pass!). However, if I right-click a single test function, and choose "Run As -> JUnit Test", I get an exception java.lang.NoSuchMethodError: org.mockito.Mockito.doAnswer(Lorg/mockito/stubbing/Answer;)Lorg/mockito/stubbing/Stubber;. Of course, the "missing" method is there if I look at the sources, and like I said the tests compile and run from the command line.

    Best I can think of is if Eclipse is trying to "help" me by providing an outdated Mockito artifact (I'm using 1.8.5 in my Maven dependencies) for the JUnit plugin, akin to how the Maven plugin can stick you with an oddball version of the Maven runtime for certain tasks.

    Is this the problem? Is it something else? Can I fix this?

    ETA: Apparently this may relate to a known issue. There's a good chance that it stems from having multiple versions of Mockito in my classpath (thanks, Maven :-/ ). I seem to have my house in order -- Eclipse can run the tests now -- but unfortunately the bug has bitten my Hudson. I have to track down how to remove the old JAR from the classpath there as well.

  • Coderer
    Coderer over 13 years
    Nice call on the multiple versions; I've been burned by this often enough I have no idea why it's not one of the first things I check. I'm rebuilding now; will accept if this fixes it :D
  • Kevin Milner
    Kevin Milner about 8 years
    I had this same issue after installing poweremock, and it's mockito extension. powermock-api-mockito-1.6.4 comes with mockito-1.10.19, and I had mockito-all-1.9.5 in my pom dependencies. Updating the pom to reflect powermock's included version resolved this issue.