Page tree
Skip to end of metadata
Go to start of metadata

Mockito now offers an Incubating, optional support for mocking final classes and methods. This is a fantastic improvement that demonstrates Mockito's everlasting quest for improving testing experience. Our ambition is that Mockito "just works" with final classes and methods. Previously they were considered unmockable, preventing the user from mocking. We already started discussing how to make this feature enabled by default. Currently, the feature is still optional as we wait for more feedback from the community.

This alternative mock maker which uses a combination of both Java instrumentation API and sub-classing rather than creating a new class to represent a mock. This way, it becomes possible to mock final types and methods.

This mock maker is turned off by default because it is based on completely different mocking mechanism that requires more feedback from the community. It can be activated explicitly by the mockito extension mechanism, just create in the classpath a file /mockito-extensions/org.mockito.plugins.MockMaker containing the value mock-maker-inline.

As a convenience, the Mockito team provides an artifact where this mock maker is preconfigured. Instead of using the mockito-core artifact, include the mockito-inline artifact in your project. Note that this artifact is likely to be discontinued once mocking of final classes and methods gets integrated into the default mock maker.

Some noteworthy notes about this mock maker:

  • Mocking final types and enums is incompatible with mock settings like :
    • explicitly serialization support withSettings().serializable()
    • extra-interfaces withSettings().extraInterfaces()
  • Some methods cannot be mocked
    • Package-visible methods of java.*
    • native methods
  • This mock maker has been designed around Java Agent runtime attachment ; this require a compatible JVM, that is part of the JDK (or Java 9 VM). When running on a non-JDK VM prior to Java 9, it is however possible to manually add the Byte Buddy Java agent jar using the -javaagent parameter upon starting the JVM.

If you are interested in more details of this feature please read the javadoc of org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker

  • No labels