Home  >  Article  >  Java  >  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

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 11:11:30281browse

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 (Problem-Focused):
* Mockito Mocking Challenge: Testing Classe

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn