Mock final class with Mockito 2

java, mockito, unit-testing

Solution

Well, I found what's wrong here, it maybe useful for other people. My project tree is wrong, I put the org.mockito.plugins.MockMaker in a directory "mockito-extension" directly in "src". This is my tree now:

- projet

- src

- com.packagePath.myPackage

- myClass

- mockito-extensions

- org.mockito.plugins.MockMaker

- test

- com.packagePath.myPackage

- myClassToTest

Problem

I'm removing Powermock from the project I'm currently working on, so I'm trying to rewrite some existing unitary test only with Mockito (mockito-core-2.2.28). When I run the test, I have the following error: org.mockito.exceptions.base.MockitoException: Cannot mock/spy class com.ExternalpackagePath.Externalclass Mockito cannot mock/spy because : - final class I know that this question has already been asked (How to mock a final class with mockito, Mock objects calling final classes static methods with Mockito), but I didn't find the answer I'm looking for. Here is an extract of my code : ``` public class MyClassToTest extends TestCase { private MyClass myClass; @Mock private Externalclass ext; // This class is final, I would like to mock it @Override protected void setUp() throws Exception { MockitoAnnotations.initMocks(this); // <<<< The exception is thrown here ext = Mockito.mock(Externalclass.class); } } ``` As mentioned in the Mockito documentation (https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2, §Mock the unmockable), I added the org.mockito.plugins.MockMaker file. This is the tree of my project : - project - src - com.packagePath.myPackage - myClass - test - com.packagePath.myPackage - myClassToTest - resources - mockito-extensions - org.mockito.plugins.MockMaker I also tries to put the "resources" directory in "src", in a subdir called "test", but the result is still the same. I thought that mocking a final was possible with Mockito v2. Does someone have an idea of what is missing here ? Thanks!

Original source

Related problems