Home > Java > javaTutorial > How to Mock Void Methods in Mockito?

How to Mock Void Methods in Mockito?

DDD
Release: 2024-12-08 03:15:11
Original
974 people have browsed it

How to Mock Void Methods in Mockito?

Mocking Void Methods with Mockito

How can one mock methods with a void return type using the Mockito framework? This particular question arises frequently in scenarios where an object method does not return a value but instead performs an action.

Overcoming the Challenge

The Mockito API offers a range of options to handle this situation, including methods like doThrow(), doAnswer(), doNothing(), and doReturn().

  • doThrow(Exception): Throws a predefined Exception when the mock method is invoked.
  • doAnswer(Answer): Allows for defining custom behavior when the mock method is called. The Answer interface accepts an InvocationOnMock object and returns an appropriate value (Void in this case).

Example Implementation

Consider the following example scenario:

public class World {

    private String state;

    // Setter for state
    public void setState(String s) {
        this.state = s;
    }
} 

public class WorldTest {

    @Test public void testingWorld() {
        World mockWorld = mock(World.class);

        // Mock the setState method using doAnswer
        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                System.out.println("Called with arguments: " + Arrays.toString(args));
                return null;
            }
        }).when(mockWorld).setState(anyString());

        // Call the mock method and observe the output
        mockWorld.setState("Mocked");
    }
}
Copy after login

By employing the doAnswer method, we can specify custom behavior for the mock setState method. In the example above, we print the arguments passed to the method, providing visibility into its invocation.

The above is the detailed content of How to Mock Void Methods in 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template