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

前端 未结 3 1265
旧时难觅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:29

    As an alternative to @JeffFairley's answer, you can leverage AtomicReference. It will act as a Holder, but I prefer this over real holders because it's defined in Java's base framework.

    // 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()
    AtomicReference reference = new AtomicReference<>();
    doAnswer(invocation -> {
        QueryResult result = (QueryResult)invocation.callRealMethod();
        reference.set(result);
        return result;
    }).when(spiedDao).find(any(User.class), any(Query.class));
    
    // execute once
    service.run();
    assertThat(reference.get()).isEqualTo(/* something */);
    
    /// change conditions ///
    
    // execute again
    service.run();
    assertThat(result.get()).isEqualTo(/* something different */);
    

    In my opinion: ResultCaptor is cool stuff that may be integrated in Mockito in the future, is widely reusable and short in syntax. But if you need that sporadically, then few lines of a lambda can be more concise

提交回复
热议问题