Photo by Shaun Meintjes on Unsplash

Mocking Final Classes and Methods

Using Mockito’s Inline Mock Maker

Kenneth Kousen
6 min readMay 3, 2023

--

https://pragprog.com/newsletter/

If you want to test a Java class whose dependencies are either final classes or classes containing final methods, what do you do? You can’t extend those classes, and by definition you can’t override the methods either.

You can find the answers to that quandary in the following video:

If you prefer text to video, please read on.

Mockito can handle mocking final classes and final methods without a problem. If you go to the Mockito home page and click on the link to the Javadocs, you’ll see a numbered list of items in the Mockito class. Scroll down a bit, and you’ll find:

Number 39 talks about mocking final types and methods, as well as enums. This capability:

  • Was added in Mockito version 2.1.0.
  • Is turned off by default (but see below).

--

--

Kenneth Kousen
The Pragmatic Programmers

Author of the books Mockito Made Clear, Help Your Boss Help You, Kotlin Cookbook, Modern Java Recipes, Gradle Recipes for Android, and Making Java Groovy