IntelliJ Integration for Mockito
This article will show you the major features of the plugin (and some of the minor ones) and how they can be useful when working with Mockito test code.
Join the DZone community and get the full member experience.
Join For FreeMockitools is an IntelliJ plugin that provides integration for Mockito.
In this article, I’d like to show you the major features of the plugin (and some of the minor ones, too) and how they can be useful when working with Mockito test code.
Although various IntelliJ plugins do exist for Mockito, they focus on one or two specific areas of it, while this one aims to provide a much broader and deeper integration with the framework and cover many more areas of it.
Annotation vs. Method-Based Mock Creation
Mockito has the following ways (among others) of creating mock objects:
@Mock
and@Spy
field annotationsMockito.mock()
andMockito.spy()
methods.
Although with some limitations, these two approaches are interchangeable.
Let’s say you have a mock created using Mockito.mock()
in one of your test methods. You realize that it needs to be used in other methods as well, so you want to convert it into a @Mock
annotated field instead.
Instead of creating one and parameterizing it with the proper mock settings manually, you can use the intention action called Convert to @Mock field to do that. This intention action takes into account the mock settings as well, so you don’t have to worry about them either.
So, the conversion like the one below will take place:
//From
Convertible convertible =
Mockito.mock(Convertible.class, Mockito.withSettings().name("name").extraInterfaces(List.class));
//to
@Mock(name = "name", extraInterfaces = List.class)
Convertible convertible;
Of course, this way of conversion works only if the mock settings, if any, are all supported by the @Mock
annotation. For instance, the usage of useConstructor(Objects…)
from MockSettings
is one such method that prevents mock creation calls to be converted to @Mock
annotated fields.
The Opposite Direction
Now, let’s say you have a @Mock
annotated field, but this time you realize it is used in only one test method, and you want to move it, thereby creating the mock via Mockito.mock()
.
A companion intention action called Convert to Mockito.mock() can do that. It converts the field, taking into account the @Mock
annotation’s attributes. If there are multiple methods in the class, it also lets you select which one to move the mock creation into.
Then, the conversion in the previous example would take place in the opposite direction.
Conversion Between Stubbing Approaches
Not including static method stubbing, there are four major ways with which stubbing in Mockito can be implemented:
Mockito.when(…).then*()
Mockito.do*().when(…)…
BDDMockito.given(…).will*()
BDDMockito.will*().given(…)…
These are, too, with some minor limitations, interchangeable.
Let’s say your manager comes to you with a request that there’s an initiative to move everyone (managers, developers, QAs, etc.) on the project to use BDD-style acceptance criteria and test cases, so from now on, you must write BDD-style unit tests.
If you’ve been using the first two stubbing approaches (not even mentioning verification), it may be “somewhat” painful to go through your project(s) and convert each affected call chain.
Specific intention actions under the umbrella Convert stubbing(s) to… title can help you with that.
They can convert each way of stubbing to any other one.
Based on the example in the image above, the following conversion would take place:
//From
BDDMockito.given(mock.doSomething())
.willThrow(IllegalArgumentException.class)
.willReturn(10);
//to
Mockito.doThrow(IllegalArgumentException.class)
.doReturn(10)
.when(mock).doSomething();
Migration From Mockito 3.x to 4.x
If you are still working with Mockito 3.x, you may have plans to migrate to 4.x. Since in 4.x, many deprecated methods were removed, your first approach might be to run code analysis on your project, see what deprecated Mockito methods are still used, and replace them manually with their supported counterparts.
A handful of inspections and their respective quick fixes, so-called Migration aids (just like what IntelliJ offers for migrating from different Java versions), are aimed at helping you convert them easily.
They can be applied one by one if you don’t have much code to migrate, or if you do have such code at many different locations, you can run project-wide code analysis and apply the quick fixes category-by-category on the Mockito migration aids results.
Project Conventions
Stubbings and verifications can be put into two major categories: the original Mockito
based approaches and the BDD-style ones in BDDMockito
. You might have a preference on which one to use, and you probably have no problem making sure you use that particular approach.
But, your project, too, might want to enforce what ways of stubbing and verification to use, to have a consistent unit test code base. In this case, it may be more difficult to enforce such a convention, depending on the size and complexity of the project, the number of developers, and other factors.
A dedicated inspection, called Enforce conventions (which is disabled by default), can enforce this, so you can save some time and effort looking for this issue during code reviews and even before that.
Users can select in the inspection settings which stubbing and verification must be used.
Combining it with the intentions mentioned in the Conversion between stubbing approaches section, you can further speed up the implementation of the correct Mockito code.
Static Code Analysis
Mockitools incorporates a handful of inspections too to provide static code analysis. I will mention a few of them in this section.
Extra Interfaces
The extra interfaces feature in mock creation makes it possible for mock objects to implement specific interfaces. These interfaces may be specified both in the @Mock
annotation and via MockSettings
.
Since it involves using interfaces and not other data types, specifying non-interface types would only be noticed after running the test.
This inspection lets you know if any of the specified types is not an interface.
Non-Mockable Types
There are certain types that Mockito is not able to mock, ones that are not advised to mock, and ones that don’t make sense to mock due to various reasons.
Such types include Java primitives and primitive wrappers, and starting from Mockito 4.1.0, types in whose type hierarchy at least one type is annotated with @DoNotMock
.
Mockitools can identify mocks with these types:
And, in the case of @DoNotMock
annotated types, it can also extract the reason from its reason
attribute, if it has any, why one should not mock those particular types:
Stubbing Checked Exceptions
The use case: you want to test some logic for when a certain method throws an exception. You stub the method to throw that particular exception, you implement the rest of the test, and you execute it.
Only after running the test do you notice (because Mockito tells you) that the exception is a checked one and must be added to the stubbed method’s throws
clause. So, you go and add it manually.
Instead of doing this, a dedicated inspection can identify checked exceptions missing from the throws
clause and provides a quick fix to add it there:
Inspections on InOrder
During the creation of an InOrder
variable, one has to specify all mock objects that are intended to be verified in order, then call the actual verifications on them.
There are two major problems regarding InOrder
s that the plugin can identify:
When there is a mock object passed into
Mockito.inOrder()
, but there is no verification called on that mock. This may mean, for instance, that the mock is either superfluously specified in the creation of theInOrder
or it actually needs to be verified.
When there is an in-order verification on a mock, but it’s not passed into
Mockito.inOrder()
. In this case, the mock may need to be specified during the creation ofInOrder
, or the verification may be removed.
Resources
I hope you found some useful tools in these sections. If you’d like to know more details about Mockitools, you can follow the links below:
Opinions expressed by DZone contributors are their own.
Comments