How to stub get / set simple types

I'm new to Mockito and I was wondering how I can drown out the get / set pair.

for instance

public interface Order { public short getStatus(); public void setStatus(short status); } 

How can I make them behave correctly:

If somewhere in the test I call setStatus(4); I would like getStatus() return 4 . How can I do that?

+4
source share
2 answers

Do you knock or taunt ?

The difference is whether you test the behavior or provide data for the test. You speak:

if somewhere in the test I call setStatus (4); I would like getStatus () to return 4.

this implies both at the same time. You either want to verify that setStatus() was called with argument 4.

 verify(mockObject).setStatus(4); 

or you want your dummy object to return 4 when getStatus() called.

 when(mockObject.getStatus()).thenReturn(4); 

Mockito has several guides that explain how to use it for each situation. I suspect that you can do both in your test (but did not check), but that would be a smell for me, since you should ideally only check the mockery of one thing in your test, everything else should be pointed . But, as always, context is everything, and maybe you need to mute one part of your object so that you can test the behavior of the other part, in which case everything will be fine.

Follow the AAA syntax and organize your test (i.e., configure and specify when ), then act (i.e. call the method on the test object), then your statements (i.e. have your verify instructions)

EDIT

it seems that in newer versions (1.8+) of mockito it is possible to do what you want, although this is not recommended. You can use Spy to create a partial layout of the object. In this case, you will need to create a Spy of your actual object, leave the getStatus() and setStatus() methods un-stubbed (so that they are actually called and used) and just delete the other methods (or just check they were supposedly named). You can read about this in section 13 Spying on real objects on this page .

+5
source

You can set the behavior of the setStatus method so that it updates the behavior of the getStatus method as follows:

  Mockito.doAnswer(invocation -> { short status = invocation.getArgumentAt(0, Short.class); Mockito.when(mockOrder.getStatus()).thenReturn(status); return null; }).when(mockOrder).setStatus(Mockito.anyShort()); 
+3
source

Source: https://habr.com/ru/post/1411464/


All Articles