How to Mock a Final Class With Mockito

How to mock a final class with mockito

Mocking final/static classes/methods is possible with Mockito v2 only.

add this in your gradle file:

testImplementation 'org.mockito:mockito-inline:2.13.0'

This is not possible with Mockito v1, from the Mockito FAQ:

What are the limitations of Mockito

  • Needs java 1.5+

  • Cannot mock final classes


...

Mock final class with Mockito 2

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

Mock final class in java using mockito library

try using this.

Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
Use the @PrepareForTest(ClassWithFinal.class) annotation at the class-level of the test case.
Use PowerMock.createMock(ClassWithFinal.class) to create a mock object for all methods of this class (let's call it mockObject).
Use PowerMock.replay(mockObject) to change the mock object to replay mode.
Use PowerMock.verify(mockObject) to change the mock object to verify mode.

Also refer this answer - link

And Tutorial.

Both look easy to implement.

Mock a method that's inside a final class using Mockito

Try to write a testable code. Example in your case, Your class is final and cannot be mocked, then your class can implement an interface, then you can absolutely mock the methods of the interface.

Your class is final and cannot be mocked

Why? Because a final class cannot be extended. By mocking a class/interface, the technique behind is it creates a subclass extends/implements the class/interface. Then if your class prevents extending by having final, you cannot mock it.

Note: you can use some power libs to mock final class (e.g. - powermockito), but I would not recommend this.

Mockito cannot mock/spy because : Final Class


mocking library for Kotlin http://mockk.io

I also used mockito before, it has so many problems when writing.

Instead, the mockk is powerful and it makes your testing easier to write and

object mocks is just for your case



Related Topics



Leave a reply



Submit