mockito: Is there a way of capturing the return value of stubbed method?

前端 未结 3 1222
旧时难觅i
旧时难觅i 2021-02-12 12:51

If I mock a method to return a new instance of some object, how can I capture the returned instance?

E.g.:

 when(mock.someMethod(anyString())).thenAnswe         


        
3条回答
  •  一个人的身影
    2021-02-12 13:47

    I wanted to do something similar, but with a spied object rather than a mock. Specifically, given a spied object, I want to capture the return value. Based on Andreas_D's answer, here's what I came up with.

    public class ResultCaptor implements Answer {
        private T result = null;
        public T getResult() {
            return result;
        }
    
        @Override
        public T answer(InvocationOnMock invocationOnMock) throws Throwable {
            result = (T) invocationOnMock.callRealMethod();
            return result;
        }
    }
    

    Intended usage:

    // spy our dao
    final Dao spiedDao = spy(dao);
    // instantiate a service that does some stuff, including a database find
    final Service service = new Service(spiedDao);
    
    // let's capture the return values from spiedDao.find()
    final ResultCaptor resultCaptor = new ResultCaptor<>();
    doAnswer(resultCaptor).when(spiedDao).find(any(User.class), any(Query.class));
    
    // execute once
    service.run();
    assertThat(resultCaptor.getResult()).isEqualTo(/* something */);
    
    /// change conditions ///
    
    // execute again
    service.run();
    assertThat(resultCaptor.getResult()).isEqualTo(/* something different */);
    

提交回复
热议问题