-1

Is there a way to return the received object in Mockito? I want to do this simulating the saving of the object in the database. Something like this:

someClass someObj = ...;

when(dataProviderMock.insert(someObj))
    .then(
          when(dataProviderMock.read(someObj.getId()))
         .thenReturn(someObj)
    );
SG Tech Edge
  • 477
  • 4
  • 16
  • there is no need to nest the statements, if the insert method returns an Object you could write it like this when(dataProviderMock.insert(eq(someObj)).thenReturn(someObj); given that the equals method of your "someObj" checks the Id. Am I getting your question right? – azl Feb 13 '20 at 14:49
  • not really. what you wrote is basically a return for the insert method. What I want is that the "read" returns the object when it was inserted. – SG Tech Edge Feb 13 '20 at 15:40

3 Answers3

1

What you are after is an ArgumentCaptor from Mockito check out this other question

Example on Mockito's argumentCaptor

Brendon Randall
  • 1,436
  • 3
  • 14
  • 25
1

I am not sure of the benefit of it, but this will work:

// Keep the saved objects in a map

 Map<Integer, Object> savedObjects = new HashMap<>(); 



// Saves the object in the map
when(dataProviderMock.insert(any(SomeClass.class))).thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                SomeClass someObj = ((SomeClass)invocation.getArgument(0));
                savedObjects.put(someObj.getId(), someObj);
                return null;
            }
        });

// retrieves the object from the map or null if it was not previously saved
when(dataProviderMock.read(any(Integer.class))).thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Integer id = ((Integer)invocation.getArgument(0));
                return savedObjects.get(id);
            }
        });
azl
  • 109
  • 1
  • 8
  • Tha lloks like what I wanted. I will test it out. Thanks. The usage is - test a controller. And I want to mock saving and retrieving users from and to the DB – SG Tech Edge Feb 13 '20 at 16:30
0

If i understand it correct, you want to return an object when you call the insert. Provided your insert function has return type of someObj. you can directly return the object using

    when(dataProviderMock.insert(someObj)).thenReturn(someObj)

If your return type is void for dataProviderMock.insert() function, you may do this:

    doNothing().doReturn(someObj).when(dataProviderMock).insert(someObj);
  • Hi, it is ideed not what I want. I want that the dataProviderMock read returns the object when it was inserted. basically read(...)==null before insertion; after read(...)==obj – SG Tech Edge Feb 13 '20 at 15:43