Home > Java > javaTutorial > How to Test Classes with Embedded `new()` Calls Using Mockito Spies?

How to Test Classes with Embedded `new()` Calls Using Mockito Spies?

Mary-Kate Olsen
Release: 2024-10-27 12:48:29
Original
914 people have browsed it

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

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:

  • Real methods are called by default (unless individually stubbed).
  • Spies can be used cautiously for legacy code scenarios.

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

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!

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