Mocking a Class with a New() Call Using Mockito
Legacy classes often instantiate objects internally, making it challenging to test them using mocking frameworks like Mockito. This becomes evident when setting up complex dependencies, such as security contexts that require external setup.
Consider the example class:
<code class="java">public class TestedClass { public LoginContext login(String user, String password) { LoginContext lc = new LoginContext("login", callbackHandler); } }</code>
We want to test this class, but the login() method instantiates a LoginContext object, complicating mocking without refactoring the code.
Can Mockito mock the LoginContext?
Yes, it is possible to mock the LoginContext class using Mockito by leveraging the powerful feature of spies. Unlike stubs, spies call the real methods of the object being spied on (unless a method has been stubbed).
Using Spies to Mock the LoginContext
To mock the LoginContext without altering the source code, we can use the following approach:
<code class="java">TestedClass tc = spy(new TestedClass()); LoginContext lcMock = mock(LoginContext.class); when(tc.login(anyString(), anyString())).thenReturn(lcMock);</code>
Conclusion
By strategically employing spies, we can effectively mock classes that instantiate objects internally, even when the original code remains untouched. This technique enables us to test such classes efficiently and ensure their behavior meets expectations.
The above is the detailed content of How Can You Mock a Class with a `new()` Call Using Mockito?. For more information, please follow other related articles on the PHP Chinese website!