简体   繁体   中英

Mockito: how to mock setter of a setter?

Let's say I've a code like this:

public response MyMethod(Request req)
{
    String id = req.getFirst().geId();
}

I've mocked the main object req : Request reqMock = mock(Request.class);

Then I've done something like:

First first = new First();
first.setId("1")
req.setFirst(first);

How do I keep mocking the members, ie getFirst() and then geId()

Thanks for helping

You can listen for the event (getting the name) and override the return value. For example:

private final First first = mock(First.class);

when(first.getFirst()).thenReturn("some_value");

You should not mock the method inputs. If you want to unit test your method. You have to call the method with real value otherwise you will not really test his behaviour

You want to mock First and have it that getFirst returns the mockFirst. See https://static.javadoc.io/org.mockito/mockito-core/2.13.0/org/mockito/Mockito.html#RETURNS_DEEP_STUBS

Once you have that then you can stub when(mockFirst.geId()).thenReturn("someString");

Personally I'd skip the deepstubs feature and do what Ole said in the comments

It seems the nested get is more your issue than the nested set. You can handle this by doing the following:

Contents mockContents = Mockito.mock(Contents.class);
Mockito.when(mockContents.geId()).thenReturn("string you want to return");

Response mockResponse = Mockito.mock(Response.class);
Mockito.when(mockResponse.getFirst()).thenReturn(mockContents);

You can chain these together as long as you need, just make sure each return is returning the mocked version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM