Mockito: how to verify method was called on an object created within a method?
To verify method calls on objects instantiated within a method, use ArgumentCaptor
or spy
features from Mockito.
Example with ArgumentCaptor
:
Example with spy
:
Master the art of method verification in encapsulated objects
Let's dive deeper into techniques for method verification in encapsulated objects, addressing complexities, resiliency, and sustainability in test design.
Unleashing the power of Factory-pattern and Dependency Injection
Enlighten your Foo
class with a BarFactory
and enjoy the benefits of Dependency Injection (DI). This will allow you to inject a mock factory during tests and effortlessly verify its interactions.
During the test, send in a mock BarFactory
, catching and verifying the Bar
instance.
Sailing with Test-Driven Mocking Strategies
By applying Test-Driven Development (TDD), our design remains clean and testable from conception. Mock dependencies through constructor, setter, or field injection using @InjectMocks
to focus on the external behaviour of our class under test, not on how it creates its dependencies.
PowerMockito: When Sherlock meets Harry (The Wizarding world of mocks!)
With PowerMockito
, you can actually mock constructor calls with the help of whenNew
method, coupled with @PrepareForTest
annotation. This is handy when you are stuck with legacy codes where refactoring could open Pandora's box!
MockitoJUnitRunner: The Mocks Marathon
Bag a smooth ride on MockitoJUnitRunner train, that saves you many initialization boilerplates. It auto-initializes your mocks and injects them into the class under test.
Best practices and future-proof strategies
Let's explore some of the contemporary practices and principles of method verification.
Designing for Testability
When it comes to design, testability is everything! Consider constructor, setter, and field injection to make your classes more flexible and easily testable.
Behaviour over Implementation
In testing, always target to verify the expected behaviour rather than poking around the internal workings. This approach often results in more resilient tests.
The Broader Picture
While verifying individual methods is great, also consider the overall impact on linked objects and system. As such, design your tests to assert these broader outcomes.
Knowing is Winning
Stay informed! Refer to official Mockito documentation and regularly engage with community-driven platforms to stay updated on fresher techniques and strategies.
Was this article helpful?