Home > Java > javaTutorial > How Can You Mock a Class with a `new()` Call Using Mockito?

How Can You Mock a Class with a `new()` Call Using Mockito?

Mary-Kate Olsen
Release: 2024-10-30 00:23:29
Original
703 people have browsed it

How Can You Mock a Class with a `new()` Call Using Mockito?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template