Home >Java >javaTutorial >How to Test Classes with Embedded `new()` Calls Using Mockito Spies?
Testing Classes with Embedded new() Calls Using Mockito
Consider a legacy class (TestedClass) that instantiates a LoginContext object using a direct new() call:
<code class="java">public class TestedClass { public LoginContext login(String user, String password) { LoginContext lc = new LoginContext("login", callbackHandler); } }</code>
Testing this class can be challenging when the LoginContext instantiation requires specific JAAS security configurations. To address this, we explore the use of Mockito to mock the LoginContext class without modifying the original source code.
Using Mockito Spies
Mockito provides a convenient mechanism called spies that allow us to create spies of real objects, which execute the following methods:
To test our class with spies, we can introduce the following code:
<code class="java">TestedClass tc = spy(new TestedClass()); LoginContext lcMock = mock(LoginContext.class); when(tc.login(anyString(), anyString())).thenReturn(lcMock);</code>
This code creates a spy of the TestedClass instance (tc ) and mocks the LoginContext class via lcMock. The when() statement stubs the login() method to return the mocked LoginContext.
Employing spies allows us to test the original class without altering its new() call mechanism, offering a flexible and effective testing approach.
The above is the detailed content of How to Test Classes with Embedded `new()` Calls Using Mockito Spies?. For more information, please follow other related articles on the PHP Chinese website!