Home > Java > javaTutorial > How to Mock Void Methods in Mockito: A Guide to doThrow, doAnswer, doNothing, and doReturn?

How to Mock Void Methods in Mockito: A Guide to doThrow, doAnswer, doNothing, and doReturn?

Susan Sarandon
Release: 2024-12-17 03:06:26
Original
430 people have browsed it

How to Mock Void Methods in Mockito:  A Guide to doThrow, doAnswer, doNothing, and doReturn?

Mocking Void Methods with Mockito

When dealing with observer patterns, mocking methods with void return types can present challenges. One such case is encountering difficulties in mocking a class with a method like addListener, which returns void.

To mock a method with no return value, Mockito provides a set of methods: doThrow(), doAnswer(), doNothing(), and doReturn(). These methods allow you to specify the behavior of the mocked method.

For instance, to specify that the addListener method throws an exception when called, you can use:

Mockito.doThrow(new Exception()).when(instance).addListener(any(Listener.class));
Copy after login

Alternatively, you can chain multiple behaviors together. For example, the following code throws an exception on the first call to addListener and then does nothing on subsequent calls:

Mockito.doThrow(new Exception()).doNothing().when(instance).addListener(any(Listener.class));
Copy after login

In the provided World class, you can mock the setState method using the doAnswer method, as shown below:

World mockWorld = mock(World.class);
doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();
        System.out.println("called with arguments: " + Arrays.toString(args));
        return null;
    }
}).when(mockWorld).setState(anyString());
Copy after login

The above is the detailed content of How to Mock Void Methods in Mockito: A Guide to doThrow, doAnswer, doNothing, and doReturn?. 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