Testing Classes with new() Operator Calls Using Mockito
Mocking classes that initialize instances using the new() operator can be challenging, especially when dealing with legacy code. One such example is the login() method in the TestedClass class, which instantiates a LoginContext object.
The challenge arises when trying to test this class using Mockito as it requires JAAS security setup prior to instantiation. Without externally calling LoginContext, it seems impossible to mock the object.
Solution: Utilizing Mockito Spies
To overcome this obstacle, Mockito provides spies, a unique feature that allows you to create spies on real objects. Spies invoke the actual methods of the spied object, but you can still mock-out or assert on specific methods if needed.
In the case of the TestedClass, the solution is as follows:
<code class="java">TestedClass tc = spy(new TestedClass()); LoginContext lcMock = mock(LoginContext.class); when(tc.login(anyString(), anyString())).thenReturn(lcMock);</code>
Here, we create a spy on the TestedClass, effectively allowing us to interact with the real methods and assert on the behavior we expect. By mocking the login() method, we can control the return value and verify the parameters passed to it.
The above is the detailed content of Here are a few title options, focusing on the question aspect and the core problem/solution: Option 1 (Direct): * How to Mock Objects Initialized with `new()` Using Mockito Spies? Option 2 (Proble. For more information, please follow other related articles on the PHP Chinese website!