Best Mockito code snippet using org.mockito.Mockito.doAnswer
Source:ConnectionProxyXATest.java  
...71    public void testXABranchCommit() throws Throwable {72        Connection connection = Mockito.mock(Connection.class);73        ValueHolder<Boolean> autoCommitOnConnection = new ValueHolder<>();74        autoCommitOnConnection.value = true;75        Mockito.doAnswer(new Answer() {76            @Override77            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {78                autoCommitOnConnection.value = (boolean)invocationOnMock.getArguments()[0];79                return null;80            }81        }).when(connection).setAutoCommit(any(Boolean.class));82        Mockito.doAnswer(new Answer() {83            @Override84            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {85                return autoCommitOnConnection.value;86            }87        }).when(connection).getAutoCommit();88        XAResource xaResource = Mockito.mock(XAResource.class);89        ValueHolder<Boolean> xaStarted = new ValueHolder<>();90        Mockito.doAnswer(new Answer() {91            @Override92            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {93                xaStarted.value = true;94                return null;95            }96        }).when(xaResource).start(any(Xid.class), any(Integer.class));97        ValueHolder<Boolean> xaEnded = new ValueHolder<>();98        Mockito.doAnswer(new Answer() {99            @Override100            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {101                xaEnded.value = true;102                return null;103            }104        }).when(xaResource).end(any(Xid.class), any(Integer.class));105        ValueHolder<Boolean> xaPrepared = new ValueHolder<>(false);106        Mockito.doAnswer(new Answer() {107            @Override108            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {109                xaPrepared.value = true;110                return null;111            }112        }).when(xaResource).prepare(any(Xid.class));113        XAConnection xaConnection = Mockito.mock(XAConnection.class);114        Mockito.when(xaConnection.getXAResource()).thenReturn(xaResource);115        BaseDataSourceResource<ConnectionProxyXA> baseDataSourceResource = Mockito.mock(BaseDataSourceResource.class);116        String xid = "xxx";117        ResourceManager resourceManager = Mockito.mock(ResourceManager.class);118        Mockito.doNothing().when(resourceManager).registerResource(any(Resource.class));119        DefaultResourceManager.get();120        DefaultResourceManager.mockResourceManager(BranchType.XA, resourceManager);121        ConnectionProxyXA connectionProxyXA = new ConnectionProxyXA(connection, xaConnection, baseDataSourceResource, xid);122        connectionProxyXA.init();123        connectionProxyXA.setAutoCommit(false);124        Assertions.assertFalse(connectionProxyXA.getAutoCommit());125        // Assert setAutoCommit = false was NEVER invoked on the wrapped connection126        Assertions.assertTrue(connection.getAutoCommit());127        // Assert XA start was invoked128        Assertions.assertTrue(xaStarted.value);129        connectionProxyXA.commit();130        Assertions.assertTrue(xaEnded.value);131        Assertions.assertTrue(xaPrepared.value);132    }133    @Test134    public void testXABranchRollback() throws Throwable {135        Connection connection = Mockito.mock(Connection.class);136        ValueHolder<Boolean> autoCommitOnConnection = new ValueHolder<>();137        autoCommitOnConnection.value = true;138        Mockito.doAnswer(new Answer() {139            @Override140            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {141                autoCommitOnConnection.value = (boolean)invocationOnMock.getArguments()[0];142                return null;143            }144        }).when(connection).setAutoCommit(any(Boolean.class));145        Mockito.doAnswer(new Answer() {146            @Override147            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {148                return autoCommitOnConnection.value;149            }150        }).when(connection).getAutoCommit();151        XAResource xaResource = Mockito.mock(XAResource.class);152        ValueHolder<Boolean> xaStarted = new ValueHolder<>();153        Mockito.doAnswer(new Answer() {154            @Override155            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {156                xaStarted.value = true;157                return null;158            }159        }).when(xaResource).start(any(Xid.class), any(Integer.class));160        ValueHolder<Boolean> xaEnded = new ValueHolder<>();161        Mockito.doAnswer(new Answer() {162            @Override163            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {164                xaEnded.value = true;165                return null;166            }167        }).when(xaResource).end(any(Xid.class), any(Integer.class));168        ValueHolder<Boolean> xaPrepared = new ValueHolder<>(false);169        Mockito.doAnswer(new Answer() {170            @Override171            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {172                xaPrepared.value = true;173                return null;174            }175        }).when(xaResource).prepare(any(Xid.class));176        XAConnection xaConnection = Mockito.mock(XAConnection.class);177        Mockito.when(xaConnection.getXAResource()).thenReturn(xaResource);178        BaseDataSourceResource<ConnectionProxyXA> baseDataSourceResource = Mockito.mock(BaseDataSourceResource.class);179        String xid = "xxx";180        ResourceManager resourceManager = Mockito.mock(ResourceManager.class);181        Mockito.doNothing().when(resourceManager).registerResource(any(Resource.class));182        DefaultResourceManager.get();183        DefaultResourceManager.mockResourceManager(BranchType.XA, resourceManager);184        ConnectionProxyXA connectionProxyXA = new ConnectionProxyXA(connection, xaConnection, baseDataSourceResource, xid);185        connectionProxyXA.init();186        connectionProxyXA.setAutoCommit(false);187        Assertions.assertFalse(connectionProxyXA.getAutoCommit());188        // Assert setAutoCommit = false was NEVER invoked on the wrapped connection189        Assertions.assertTrue(connection.getAutoCommit());190        // Assert XA start was invoked191        Assertions.assertTrue(xaStarted.value);192        connectionProxyXA.rollback();193        Assertions.assertTrue(xaEnded.value);194        // Not prepared195        Assertions.assertFalse(xaPrepared.value);196    }197    @Test198    public void testClose() throws Throwable {199        Connection connection = Mockito.mock(Connection.class);200        Mockito.when(connection.getAutoCommit()).thenReturn(true);201        ValueHolder<Boolean> closed = new ValueHolder<>();202        closed.value = false;203        Mockito.doAnswer(new Answer() {204            @Override205            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {206                closed.value = true;207                return null;208            }209        }).when(connection).close();210        XAConnection xaConnection = Mockito.mock(XAConnection.class);211        BaseDataSourceResource<ConnectionProxyXA> baseDataSourceResource = Mockito.mock(BaseDataSourceResource.class);212        String xid = "xxx";213        ConnectionProxyXA connectionProxyXA1 = new ConnectionProxyXA(connection, xaConnection, baseDataSourceResource, xid);214        connectionProxyXA1.init();215        // Kept216        connectionProxyXA1.setHeld(true);217        // call close on proxy218        connectionProxyXA1.close();219        // Assert the original connection was NOT closed220        Assertions.assertFalse(closed.value);221        ConnectionProxyXA connectionProxyXA2 = new ConnectionProxyXA(connection, xaConnection, baseDataSourceResource, xid);222        connectionProxyXA2.init();223        // Kept224        connectionProxyXA2.setHeld(false);225        // call close on proxy226        connectionProxyXA2.close();227        // Assert the original connection was ALSO closed228        Assertions.assertTrue(closed.value);229    }230    @Test231    public void testXACommit() throws Throwable {232        Connection connection = Mockito.mock(Connection.class);233        Mockito.when(connection.getAutoCommit()).thenReturn(true);234        XAResource xaResource = Mockito.mock(XAResource.class);235        ValueHolder<Boolean> xaCommitted = new ValueHolder<>(false);236        Mockito.doAnswer(new Answer() {237            @Override238            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {239                xaCommitted.value = true;240                return null;241            }242        }).when(xaResource).commit(any(Xid.class), any(Boolean.class));243        ValueHolder<Boolean> xaRolledback = new ValueHolder<>(false);244        Mockito.doAnswer(new Answer() {245            @Override246            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {247                xaRolledback.value = true;248                return null;249            }250        }).when(xaResource).rollback(any(Xid.class));251        XAConnection xaConnection = Mockito.mock(XAConnection.class);252        Mockito.when(xaConnection.getXAResource()).thenReturn(xaResource);253        BaseDataSourceResource<ConnectionProxyXA> baseDataSourceResource = Mockito.mock(BaseDataSourceResource.class);254        String xid = "xxx";255        ConnectionProxyXA connectionProxyXA = new ConnectionProxyXA(connection, xaConnection, baseDataSourceResource, xid);256        connectionProxyXA.init();257        connectionProxyXA.xaCommit("xxx", 123L, null);258        Assertions.assertTrue(xaCommitted.value);259        Assertions.assertFalse(xaRolledback.value);260    }261    @Test262    public void testXARollback() throws Throwable {263        Connection connection = Mockito.mock(Connection.class);264        Mockito.when(connection.getAutoCommit()).thenReturn(true);265        XAResource xaResource = Mockito.mock(XAResource.class);266        ValueHolder<Boolean> xaCommitted = new ValueHolder<>(false);267        Mockito.doAnswer(new Answer() {268            @Override269            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {270                xaCommitted.value = true;271                return null;272            }273        }).when(xaResource).commit(any(Xid.class), any(Boolean.class));274        ValueHolder<Boolean> xaRolledback = new ValueHolder<>(false);275        Mockito.doAnswer(new Answer() {276            @Override277            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {278                xaRolledback.value = true;279                return null;280            }281        }).when(xaResource).rollback(any(Xid.class));282        XAConnection xaConnection = Mockito.mock(XAConnection.class);283        Mockito.when(xaConnection.getXAResource()).thenReturn(xaResource);284        BaseDataSourceResource<ConnectionProxyXA> baseDataSourceResource = Mockito.mock(BaseDataSourceResource.class);285        String xid = "xxx";286        ConnectionProxyXA connectionProxyXA = new ConnectionProxyXA(connection, xaConnection, baseDataSourceResource, xid);287        connectionProxyXA.init();288        connectionProxyXA.xaRollback("xxx", 123L, null);289        Assertions.assertFalse(xaCommitted.value);...Source:OfficalTest_Part_4.java  
...142     */143    @Test144    public void step_37() {145//        // answer by returning 12 every time146//        doAnswer(invocation -> 12).when(mock).doSomething();147//148//        // answer by using one of the parameters - converting into the right149//        // type as your go - in this case, returning the length of the second string parameter150//        // as the answer. This gets long-winded quickly, with casting of parameters.151//        doAnswer(invocation -> ((String)invocation.getArgument(1)).length())152//                .when(mock).doSomething(anyString(), anyString(), anyString());153//154//        // Example interface to be mocked has a function like:155//        void execute(String operand, Callback callback);156//157//        // the example callback has a function and the class under test158//        // will depend on the callback being invoked159//        void receive(String item);160//161//        // Java 8 - style 1162//        doAnswer(AdditionalAnswers.answerVoid((operand, callback) -> callback.receive("dummy"))163//                .when(mock).execute(anyString(), any(Callback.class));164//165//        // Java 8 - style 2 - assuming static import of AdditionalAnswers166//        doAnswer(answerVoid((String operand, Callback callback) -> callback.receive("dummy"))167//                .when(mock).execute(anyString(), any(Callback.class));168//169//        // Java 8 - style 3 - where mocking function to is a static member of test class170//        private static void dummyCallbackImpl(String operation, Callback callback) {171//            callback.receive("dummy");172//        }173//174//        doAnswer(answerVoid(TestClass::dummyCallbackImpl)175//                .when(mock).execute(anyString(), any(Callback.class));176//177//        // Java 7178//        doAnswer(answerVoid(new VoidAnswer2() {179//            public void answer(String operation, Callback callback) {180//                callback.receive("dummy");181//            }})).when(mock).execute(anyString(), any(Callback.class));182//183//        // returning a value is possible with the answer() function184//        // and the non-void version of the functional interfaces185//        // so if the mock interface had a method like186//        boolean isSameString(String input1, String input2);187//188//        // this could be mocked189//        // Java 8190//        doAnswer(AdditionalAnswers.answer((input1, input2) -> input1.equals(input2))))191//        .when(mock).execute(anyString(), anyString());192//193//        // Java 7194//        doAnswer(answer(new Answer2() {195//            public String answer(String input1, String input2) {196//                return input1 + input2;197//            }})).when(mock).execute(anyString(), anyString());198    }199    /*200     * Meta data and generic type retention (Since 2.1.0)201     * Mockitoç°å¨ä¿çmockedæ¹æ³ä»¥åç±»åä¸ç注éä¿¡æ¯ï¼å°±åä½ä¸ºæ³å屿§æ°æ®ä¸æ ·ã202     * 以åï¼æ¨¡æç±»å没æä¿ç对类åçæ³¨éï¼é¤éå®ä»¬è¢«æ¾å¼å°ç»§æ¿ï¼å¹¶ä¸ä»æªå¨æ¹æ³ä¸ä¿ç注éã203     * å æ¤ï¼ç°å¨çæ¡ä»¶å¦ä¸ï¼204     * 彿¶ç¨Java8æ¶ï¼Mockitoç°å¨ä¹ä¼ä¿çç±»åæ³¨è§£ï¼è¿æ¯é»è®¤è¡ä¸ºï¼å¦æä½¿ç¨å¦ä¸ä¸ªMockMakerå¯è½ä¸ä¼ä¿çã205     */206    /**207     * {@see Mockito208     * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#38...Source:MockParserMapFactories.java  
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT license.3package com.microsoft.maps.moduletoolstest;4import static org.mockito.Mockito.doAnswer;5import android.graphics.Bitmap;6import android.graphics.BitmapFactory;7import android.graphics.Color;8import androidx.annotation.NonNull;9import com.microsoft.maps.Geopath;10import com.microsoft.maps.Geopoint;11import com.microsoft.maps.MapElementLayer;12import com.microsoft.maps.MapIcon;13import com.microsoft.maps.MapImage;14import com.microsoft.maps.MapPolygon;15import com.microsoft.maps.MapPolyline;16import com.microsoft.maps.MockMapElementCollection;17import com.microsoft.maps.moduletools.MapFactories;18import java.io.InputStream;19import java.util.ArrayList;20import java.util.concurrent.atomic.AtomicReference;21import org.mockito.Mockito;22public class MockParserMapFactories implements MapFactories {23  @Override24  public MapElementLayer createMapElementLayer() {25    MapElementLayer layer = Mockito.mock(MapElementLayer.class);26    MockMapElementCollection mockElementCollection = new MockMapElementCollection(layer);27    Mockito.doAnswer(invocation -> mockElementCollection).when(layer).getElements();28    return layer;29  }30  @Override31  public MapIcon createMapIcon() {32    MapIcon icon = Mockito.mock(MapIcon.class);33    // location must be final for use within the 'doAnswer' clause34    // AtomicReference used as a wrapper class to capture changes to location35    final AtomicReference<Geopoint> location = new AtomicReference<>();36    Mockito.doAnswer(37            invocation -> {38              location.set(invocation.getArgument(0));39              return true;40            })41        .when(icon)42        .setLocation(Mockito.any(Geopoint.class));43    Mockito.doAnswer(invocation -> location.get()).when(icon).getLocation();44    final AtomicReference<String> title = new AtomicReference<>();45    Mockito.doAnswer(46            invocation -> {47              title.set(invocation.getArgument(0));48              return true;49            })50        .when(icon)51        .setTitle(Mockito.any(String.class));52    Mockito.doAnswer(invocation -> title.get()).when(icon).getTitle();53    final AtomicReference<MapImage> image = new AtomicReference<MapImage>();54    Mockito.doAnswer(55            invocation -> {56              image.set(invocation.getArgument(0));57              return true;58            })59        .when(icon)60        .setImage(Mockito.any(MapImage.class));61    Mockito.doAnswer(invocation -> image.get()).when(icon).getImage();62    return icon;63  }64  @Override65  public MapPolyline createMapPolyline() {66    MapPolyline polyline = Mockito.mock(MapPolyline.class);67    // paths must be final for use within the 'doAnswer' clause68    // AtomicReference used as a wrapper class to capture changes to paths69    final AtomicReference<Geopath> paths = new AtomicReference();70    Mockito.doAnswer(71            invocation -> {72              paths.set(invocation.getArgument(0));73              return true;74            })75        .when(polyline)76        .setPath(Mockito.any(Geopath.class));77    Mockito.doAnswer(invocation -> paths.get()).when(polyline).getPath();78    final AtomicReference<Integer> strokeWidth = new AtomicReference();79    strokeWidth.set(1);80    Mockito.doAnswer(81            invocation -> {82              strokeWidth.set(invocation.getArgument(0));83              return true;84            })85        .when(polyline)86        .setStrokeWidth(Mockito.anyInt());87    Mockito.doAnswer(invocation -> strokeWidth.get()).when(polyline).getStrokeWidth();88    final AtomicReference<Integer> strokeColor = new AtomicReference();89    // set the default value90    strokeColor.set(Color.BLUE);91    doAnswer(92            invocation -> {93              strokeColor.set(invocation.getArgument(0));94              return true;95            })96        .when(polyline)97        .setStrokeColor(Mockito.anyInt());98    doAnswer(invocation -> strokeColor.get()).when(polyline).getStrokeColor();99    return polyline;100  }101  @Override102  public MapPolygon createMapPolygon() {103    MapPolygon polygon = Mockito.mock(MapPolygon.class);104    // paths must be final for use within the 'doAnswer' clause105    // AtomicReference used as a wrapper class to capture changes to paths106    final AtomicReference<ArrayList<Geopath>> paths = new AtomicReference(new ArrayList<Geopath>());107    Mockito.doAnswer(108            invocation -> {109              paths.set(invocation.getArgument(0));110              return true;111            })112        .when(polygon)113        .setPaths(Mockito.anyList());114    Mockito.doAnswer(invocation -> paths.get()).when(polygon).getPaths();115    final AtomicReference<Integer> fillColor = new AtomicReference();116    // set the default value117    fillColor.set(Color.BLUE);118    doAnswer(119            invocation -> {120              fillColor.set(invocation.getArgument(0));121              return true;122            })123        .when(polygon)124        .setFillColor(Mockito.anyInt());125    doAnswer(invocation -> fillColor.get()).when(polygon).getFillColor();126    final AtomicReference<Integer> strokeColor = new AtomicReference();127    // set the default value128    strokeColor.set(Color.BLUE);129    doAnswer(130            invocation -> {131              strokeColor.set(invocation.getArgument(0));132              return true;133            })134        .when(polygon)135        .setStrokeColor(Mockito.anyInt());136    doAnswer(invocation -> strokeColor.get()).when(polygon).getStrokeColor();137    final AtomicReference<Integer> strokeWidth = new AtomicReference();138    // set the default value139    strokeWidth.set(1);140    doAnswer(141            invocation -> {142              strokeWidth.set(invocation.getArgument(0));143              return true;144            })145        .when(polygon)146        .setStrokeWidth(Mockito.anyInt());147    doAnswer(invocation -> strokeWidth.get()).when(polygon).getStrokeWidth();148    return polygon;149  }150  public MapImage createMapImage(@NonNull InputStream inputStream) {151    MapImage mapImage = Mockito.mock(MapImage.class);152    // image must be final for use within the 'doAnswer' clause153    // AtomicReference used as a wrapper class to capture changes to inputStream154    final AtomicReference<Bitmap> image = new AtomicReference<>();155    image.set(BitmapFactory.decodeStream(inputStream));156    Mockito.doAnswer(invocation -> image.get()).when(mapImage).getBitmap();157    return mapImage;158  }159}...Source:InternalGuavaSpanStoreAdapterTest.java  
...29import static org.assertj.core.api.Assertions.assertThat;30import static org.hamcrest.core.Is.isA;31import static org.mockito.Matchers.any;32import static org.mockito.Matchers.eq;33import static org.mockito.Mockito.doAnswer;34import static zipkin.TestObjects.LINKS;35import static zipkin.TestObjects.TRACE;36public class InternalGuavaSpanStoreAdapterTest {37  @Rule38  public MockitoRule mocks = MockitoJUnit.rule();39  @Rule40  public ExpectedException thrown = ExpectedException.none();41  @Mock42  private AsyncSpanStore asyncSpanStore;43  private GuavaSpanStore spanStore;44  @Before45  public void setUp() throws Exception {46    spanStore = new InternalGuavaSpanStoreAdapter(asyncSpanStore);47  }48  @Test49  public void getTraces_success() throws Exception {50    QueryRequest request = QueryRequest.builder().build();51    doAnswer(answer(c -> c.onSuccess(asList(TRACE))))52        .when(asyncSpanStore).getTraces(eq(request), any(Callback.class));53    assertThat(spanStore.getTraces(request).get()).containsExactly(TRACE);54  }55  @Test56  public void getTraces_exception() throws Exception {57    QueryRequest request = QueryRequest.builder().build();58    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))59        .when(asyncSpanStore).getTraces(eq(request), any(Callback.class));60    thrown.expect(ExecutionException.class);61    thrown.expectCause(isA(IllegalStateException.class));62    spanStore.getTraces(request).get();63  }64  @Test65  public void getTrace_success() throws Exception {66    doAnswer(answer(c -> c.onSuccess(TRACE)))67        .when(asyncSpanStore).getTrace(eq(1L), any(Callback.class));68    assertThat(spanStore.getTrace(1L).get()).isEqualTo(TRACE);69  }70  @Test71  public void getTrace_exception() throws Exception {72    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))73        .when(asyncSpanStore).getTrace(eq(1L), any(Callback.class));74    thrown.expect(ExecutionException.class);75    thrown.expectCause(isA(IllegalStateException.class));76    spanStore.getTrace(1L).get();77  }78  @Test79  public void getRawTrace_success() throws Exception {80    doAnswer(answer(c -> c.onSuccess(TRACE)))81        .when(asyncSpanStore).getRawTrace(eq(1L), any(Callback.class));82    assertThat(spanStore.getRawTrace(1L).get()).isEqualTo(TRACE);83  }84  @Test85  public void getRawTrace_exception() throws Exception {86    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))87        .when(asyncSpanStore).getRawTrace(eq(1L), any(Callback.class));88    thrown.expect(ExecutionException.class);89    thrown.expectCause(isA(IllegalStateException.class));90    spanStore.getRawTrace(1L).get();91  }92  @Test93  public void getServiceNames_success() throws Exception {94    doAnswer(answer(c -> c.onSuccess(asList("service1", "service2"))))95        .when(asyncSpanStore).getServiceNames(any(Callback.class));96    assertThat(spanStore.getServiceNames().get()).containsExactly("service1", "service2");97  }98  @Test99  public void getServiceNames_exception() throws Exception {100    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))101        .when(asyncSpanStore).getServiceNames(any(Callback.class));102    thrown.expect(ExecutionException.class);103    thrown.expectCause(isA(IllegalStateException.class));104    spanStore.getServiceNames().get();105  }106  @Test107  public void getSpanNames_success() throws Exception {108    doAnswer(answer(c -> c.onSuccess(asList("span1", "span2"))))109        .when(asyncSpanStore).getSpanNames(eq("service"), any(Callback.class));110    assertThat(spanStore.getSpanNames("service").get()).containsExactly("span1", "span2");111  }112  @Test113  public void getSpanNames_exception() throws Exception {114    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))115        .when(asyncSpanStore).getSpanNames(eq("service"), any(Callback.class));116    thrown.expect(ExecutionException.class);117    thrown.expectCause(isA(IllegalStateException.class));118    spanStore.getSpanNames("service").get();119  }120  @Test121  public void getDependencies_success() throws Exception {122    doAnswer(answer(c -> c.onSuccess(LINKS)))123        .when(asyncSpanStore).getDependencies(eq(1L), eq(0L), any(Callback.class));124    assertThat(spanStore.getDependencies(1L, 0L).get()).containsExactlyElementsOf(LINKS);125  }126  @Test127  public void getDependencies_exception() throws Exception {128    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))129        .when(asyncSpanStore).getDependencies(eq(1L), eq(0L), any(Callback.class));130    thrown.expect(ExecutionException.class);131    thrown.expectCause(isA(IllegalStateException.class));132    spanStore.getDependencies(1L, 0L).get();133  }134  static <T> Answer answer(Consumer<Callback<T>> onCallback) {135    return invocation -> {136      onCallback.accept((Callback) invocation.getArguments()[invocation.getArguments().length - 1]);137      return null;138    };139  }140}...Source:PowerMockitoStubber.java  
...24 */25public interface PowerMockitoStubber extends Stubber {26	/**27	 * Allows to choose a static method when stubbing in28	 * doThrow()|doAnswer()|doNothing()|doReturn() style29	 * <p>30	 * Example:31	 * 32	 * <pre>33	 * doThrow(new RuntimeException()).when(StaticList.class);34	 * StaticList.clear();35	 * 36	 * //following throws RuntimeException:37	 * StaticList.clear();38	 * </pre>39	 * 40	 * Read more about those methods:41	 * <p>42	 * {@link Mockito#doThrow(Throwable)}43	 * <p>44	 * {@link Mockito#doAnswer(Answer)}45	 * <p>46	 * {@link Mockito#doNothing()}47	 * <p>48	 * {@link Mockito#doReturn(Object)}49	 * <p>50	 * 51	 * See examples in javadoc for {@link Mockito}52	 */53	void when(Class<?> classMock);54	/**55	 * Allows to mock a private instance method when stubbing in56	 * doThrow()|doAnswer()|doNothing()|doReturn() style.57	 * <p>58	 * Example:59	 * 60	 * <pre>61	 * doThrow(new RuntimeException()).when(instance, method("myMethod")).withNoArguments();62	 * </pre>63	 * 64	 * Read more about those methods:65	 * <p>66	 * {@link Mockito#doThrow(Throwable)}67	 * <p>68	 * {@link Mockito#doAnswer(Answer)}69	 * <p>70	 * {@link Mockito#doNothing()}71	 * <p>72	 * {@link Mockito#doReturn(Object)}73	 * <p>74	 * 75	 * See examples in javadoc for {@link Mockito}76	 */77	<T> PrivatelyExpectedArguments when(T mock, Method method) throws Exception;78	/**79	 * Allows to mock a private instance method based on the parameters when80	 * stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style.81	 * <p>82	 * Example:83	 * 84	 * <pre>85	 * doThrow(new RuntimeException()).when(instance, parameter1, parameter2);86	 * </pre>87	 * 88	 * Read more about those methods:89	 * <p>90	 * {@link Mockito#doThrow(Throwable)}91	 * <p>92	 * {@link Mockito#doAnswer(Answer)}93	 * <p>94	 * {@link Mockito#doNothing()}95	 * <p>96	 * {@link Mockito#doReturn(Object)}97	 * <p>98	 * 99	 * See examples in javadoc for {@link Mockito}100	 */101	<T> void when(T mock, Object... arguments) throws Exception;102	/**103	 * Allows to mock a private instance method based on method name and104	 * parameters when stubbing in doThrow()|doAnswer()|doNothing()|doReturn()105	 * style.106	 * <p>107	 * Example:108	 * 109	 * <pre>110	 * doThrow(new RuntimeException()).when(instance, "methodName", parameter1, parameter2);111	 * </pre>112	 * 113	 * Read more about those methods:114	 * <p>115	 * {@link Mockito#doThrow(Throwable)}116	 * <p>117	 * {@link Mockito#doAnswer(Answer)}118	 * <p>119	 * {@link Mockito#doNothing()}120	 * <p>121	 * {@link Mockito#doReturn(Object)}122	 * <p>123	 * 124	 * See examples in javadoc for {@link Mockito}125	 */126	<T> void when(T mock, String methodToExpect, Object... arguments) throws Exception;127	/**128	 * Allows to mock a static private method when stubbing in129	 * doThrow()|doAnswer()|doNothing()|doReturn() style.130	 * <p>131	 * Example:132	 * 133	 * <pre>134	 * doThrow(new RuntimeException()).when(MyClass.class, method("myMethod")).withNoArguments();135	 * </pre>136	 * 137	 * Read more about those methods:138	 * <p>139	 * {@link Mockito#doThrow(Throwable)}140	 * <p>141	 * {@link Mockito#doAnswer(Answer)}142	 * <p>143	 * {@link Mockito#doNothing()}144	 * <p>145	 * {@link Mockito#doReturn(Object)}146	 * <p>147	 * 148	 * See examples in javadoc for {@link Mockito}149	 */150	<T> PrivatelyExpectedArguments when(Class<T> classMock, Method method) throws Exception;151	/**152	 * Allows to mock a static private method based on the parameters when153	 * stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style.154	 * <p>155	 * Example:156	 * 157	 * <pre>158	 * doThrow(new RuntimeException()).when(MyClass.class, parameter1, parameter2);159	 * </pre>160	 * 161	 * Read more about those methods:162	 * <p>163	 * {@link Mockito#doThrow(Throwable)}164	 * <p>165	 * {@link Mockito#doAnswer(Answer)}166	 * <p>167	 * {@link Mockito#doNothing()}168	 * <p>169	 * {@link Mockito#doReturn(Object)}170	 * <p>171	 * 172	 * See examples in javadoc for {@link Mockito}173	 */174	<T> void when(Class<T> classMock, Object... arguments) throws Exception;175	/**176	 * Allows to mock a static private method based on method name and177	 * parameters when stubbing in doThrow()|doAnswer()|doNothing()|doReturn()178	 * style.179	 * <p>180	 * Example:181	 * 182	 * <pre>183	 * doThrow(new RuntimeException()).when(MyClass.class, "methodName", parameter1, parameter2);184	 * </pre>185	 * 186	 * Read more about those methods:187	 * <p>188	 * {@link Mockito#doThrow(Throwable)}189	 * <p>190	 * {@link Mockito#doAnswer(Answer)}191	 * <p>192	 * {@link Mockito#doNothing()}193	 * <p>194	 * {@link Mockito#doReturn(Object)}195	 * <p>196	 * 197	 * See examples in javadoc for {@link Mockito}198	 */199	<T> void when(Class<T> classMock, String methodToExpect, Object... parameters) throws Exception;200}...Source:InternalAsyncToBlockingSpanStoreAdapterTest.java  
...24import static java.util.Arrays.asList;25import static org.assertj.core.api.Assertions.assertThat;26import static org.mockito.Matchers.any;27import static org.mockito.Matchers.eq;28import static org.mockito.Mockito.doAnswer;29import static zipkin.TestObjects.LINKS;30import static zipkin.TestObjects.TRACE;31public class InternalAsyncToBlockingSpanStoreAdapterTest {32  @Rule33  public MockitoRule mocks = MockitoJUnit.rule();34  @Rule35  public ExpectedException thrown = ExpectedException.none();36  @Mock37  private AsyncSpanStore delegate;38  private InternalAsyncToBlockingSpanStoreAdapter spanStore;39  @Before40  public void setUp() {41    spanStore = new InternalAsyncToBlockingSpanStoreAdapter(delegate);42  }43  @Test44  public void getTraces_success() {45    QueryRequest request = QueryRequest.builder().serviceName("service").endTs(1000L).build();46    doAnswer(answer(c -> c.onSuccess(asList(TRACE))))47        .when(delegate).getTraces(eq(request), any(Callback.class));48    assertThat(spanStore.getTraces(request)).containsExactly(TRACE);49  }50  @Test51  public void getTraces_exception() {52    QueryRequest request = QueryRequest.builder().serviceName("service").endTs(1000L).build();53    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))54        .when(delegate).getTraces(eq(request), any(Callback.class));55    thrown.expect(IllegalStateException.class);56    spanStore.getTraces(request);57  }58  @Test59  public void getTrace_success() {60    doAnswer(answer(c -> c.onSuccess(TRACE)))61        .when(delegate).getTrace(eq(1L), any(Callback.class));62    assertThat(spanStore.getTrace(1L)).isEqualTo(TRACE);63  }64  @Test65  public void getTrace_exception() {66    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))67        .when(delegate).getTrace(eq(1L), any(Callback.class));68    thrown.expect(IllegalStateException.class);69    spanStore.getTrace(1L);70  }71  @Test72  public void getRawTrace_success() {73    doAnswer(answer(c -> c.onSuccess(TRACE)))74        .when(delegate).getRawTrace(eq(1L), any(Callback.class));75    assertThat(spanStore.getRawTrace(1L)).isEqualTo(TRACE);76  }77  @Test78  public void getRawTrace_exception() {79    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))80        .when(delegate).getRawTrace(eq(1L), any(Callback.class));81    thrown.expect(IllegalStateException.class);;82    spanStore.getRawTrace(1L);83  }84  @Test85  public void getServiceNames_success() {86    doAnswer(answer(c -> c.onSuccess(asList("service1", "service2"))))87        .when(delegate).getServiceNames(any(Callback.class));88    assertThat(spanStore.getServiceNames()).containsExactly("service1", "service2");89  }90  @Test91  public void getServiceNames_exception() {92    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))93        .when(delegate).getServiceNames(any(Callback.class));94    thrown.expect(IllegalStateException.class);95    spanStore.getServiceNames();96  }97  @Test98  public void getSpanNames_success() {99    doAnswer(answer(c -> c.onSuccess(asList("span1", "span2"))))100        .when(delegate).getSpanNames(eq("service"), any(Callback.class));101    assertThat(spanStore.getSpanNames("service")).containsExactly("span1", "span2");102  }103  @Test104  public void getSpanNames_exception() {105    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))106        .when(delegate).getSpanNames(eq("service"), any(Callback.class));107    thrown.expect(IllegalStateException.class);108    spanStore.getSpanNames("service");109  }110  @Test111  public void getDependencies_success() {112    doAnswer(answer(c -> c.onSuccess(LINKS)))113        .when(delegate).getDependencies(eq(1L), eq(0L), any(Callback.class));114    assertThat(spanStore.getDependencies(1L, 0L)).containsExactlyElementsOf(LINKS);115  }116  @Test117  public void getDependencies_exception() {118    doAnswer(answer(c -> c.onError(new IllegalStateException("failed"))))119        .when(delegate).getDependencies(eq(1L), eq(0L), any(Callback.class));120    thrown.expect(IllegalStateException.class);;121    spanStore.getDependencies(1L, 0L);122  }123  static <T> Answer answer(Consumer<Callback<T>> onCallback) {124    return invocation -> {125      onCallback.accept((Callback) invocation.getArguments()[invocation.getArguments().length - 1]);126      return null;127    };128  }129}...Source:Stubber.java  
...67import org.mockito.Mockito;89/**10 * Allows to choose a method when stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style11 * <p> 12 * Example:13 * <pre>14 *   doThrow(new RuntimeException()).when(mockedList).clear();15 *   16 *   //following throws RuntimeException:17 *   mockedList.clear();18 * </pre>19 * 20 * Also useful when stubbing consecutive calls:21 * 22 * <pre>23 *   doThrow(new RuntimeException("one")).24 *   doThrow(new RuntimeException("two"))25 *   .when(mock).someVoidMethod();26 * </pre>27 * 28 * Read more about those methods:29 * <p>30 * {@link Mockito#doThrow(Throwable)}31 * <p>32 * {@link Mockito#doAnswer(Answer)}33 * <p>34 * {@link Mockito#doNothing()}35 * <p>36 * {@link Mockito#doReturn(Object)}37 * <p>38 * 39 * See examples in javadoc for {@link Mockito}40 */41@SuppressWarnings("unchecked")42public interface Stubber {4344    /**45     * Allows to choose a method when stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style46     * <p> 47     * Example:48     * <pre>49     *   doThrow(new RuntimeException())50     *   .when(mockedList).clear();51     *   52     *   //following throws RuntimeException:53     *   mockedList.clear();54     * </pre>55     * 56     * Read more about those methods:57     * <p>58     * {@link Mockito#doThrow(Throwable)}59     * <p>60     * {@link Mockito#doAnswer(Answer)}61     * <p>62     * {@link Mockito#doNothing()}63     * <p>64     * {@link Mockito#doReturn(Object)}65     * <p>66     * 67     *  See examples in javadoc for {@link Mockito}68     * 69     * @param mock70     * @return select method for stubbing71     */72    <T> T when(T mock);7374    /**75     * Use it for stubbing consecutive calls in {@link Mockito#doThrow(Throwable)} style:76     * <pre>77     *   doThrow(new RuntimeException("one")).78     *   doThrow(new RuntimeException("two"))79     *   .when(mock).someVoidMethod();80     * </pre>81     * See javadoc for {@link Mockito#doThrow(Throwable)}82     * 83     * @param toBeThrown to be thrown when the stubbed method is called84     * @return stubber - to select a method for stubbing85     */86    Stubber doThrow(Throwable toBeThrown);87    88    /**89     * Use it for stubbing consecutive calls in {@link Mockito#doAnswer(Answer)} style:90     * <pre>91     *   doAnswer(answerOne).92     *   doAnswer(answerTwo)93     *   .when(mock).someVoidMethod();94     * </pre>95     * See javadoc for {@link Mockito#doAnswer(Answer)}96     * 97     * @param answer to answer when the stubbed method is called98     * @return stubber - to select a method for stubbing99     */100    Stubber doAnswer(Answer answer);    101    102    /**103     * Use it for stubbing consecutive calls in {@link Mockito#doNothing()} style:104     * <pre>105     *   doNothing().106     *   doThrow(new RuntimeException("two"))107     *   .when(mock).someVoidMethod();108     * </pre>109     * See javadoc for {@link Mockito#doNothing()}110     * 111     * @return stubber - to select a method for stubbing112     */113    Stubber doNothing();114    
...Source:BaseUnitTest.java  
...44        System.out.println(invocation.getMethod().getName().toUpperCase() + "/[" + tag + "] " + msg);45        return null;46      }47    };48    PowerMockito.doAnswer(logAnswer).when(Log.class, "d", anyString(), anyString());49    PowerMockito.doAnswer(logAnswer).when(Log.class, "i", anyString(), anyString());50    PowerMockito.doAnswer(logAnswer).when(Log.class, "w", anyString(), anyString());51    PowerMockito.doAnswer(logAnswer).when(Log.class, "e", anyString(), anyString());52    PowerMockito.doAnswer(new Answer<Boolean>() {53      @Override54      public Boolean answer(InvocationOnMock invocation) throws Throwable {55        final String s = (String)invocation.getArguments()[0];56        return s == null || s.length() == 0;57      }58    }).when(TextUtils.class, "isEmpty", anyString());59    when(sharedPreferences.getString(anyString(), anyString())).thenReturn("");60    when(sharedPreferences.getLong(anyString(), anyLong())).thenReturn(0L);61    when(sharedPreferences.getInt(anyString(), anyInt())).thenReturn(0);62    when(sharedPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(false);63    when(sharedPreferences.getFloat(anyString(), anyFloat())).thenReturn(0f);64    when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPreferences);65    when(context.getPackageName()).thenReturn("org.thoughtcrime.securesms");66  }...doAnswer
Using AI Code Generation
1import static org.mockito.Mockito.doAnswer;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4import java.util.ArrayList;5import java.util.List;6import org.junit.Assert;7import org.junit.Test;8import org.mockito.invocation.InvocationOnMock;9import org.mockito.stubbing.Answer;10public class MockitoDoAnswerExample {11    public void testDoAnswer() {12        List mockedList = mock(List.class);13        doAnswer(new Answer() {14            public Object answer(InvocationOnMock invocation) {15                Object[] args = invocation.getArguments();16                Object mock = invocation.getMock();17                return "called with arguments: " + args;18            }19        }).when(mockedList).get(0);20        System.out.println(mockedList.get(0));21        Assert.assertEquals("called with arguments: foo", mockedList.get(0));22    }23    public void testDoAnswerWithRealCall() {24        ArrayList<String> mockedList = mock(ArrayList.class);25        doAnswer(new Answer() {26            public Object answer(InvocationOnMock invocation) {27                Object[] args = invocation.getArguments();28                Object mock = invocation.getMock();29                return "called with arguments: " + args;30            }31        }).when(mockedList).add("test");32        mockedList.add("test");33        System.out.println(mockedList.get(0));34        Assert.assertEquals("called with arguments: foo", mockedList.get(0));35    }36}doAnswer
Using AI Code Generation
1package com.automationrhapsody.mockito;2import static org.mockito.Mockito.doAnswer;3import static org.mockito.Mockito.mock;4import java.util.LinkedList;5import org.junit.Test;6import org.mockito.invocation.InvocationOnMock;7import org.mockito.stubbing.Answer;8public class DoAnswerTest {9    public void testDoAnswer() {10        LinkedList mockedList = mock(LinkedList.class);11        doAnswer(new Answer() {12            public Object answer(InvocationOnMock invocation) {13                Object[] args = invocation.getArguments();14                Object mock = invocation.getMock();15                System.out.println("called with arguments: " + args[0]);16                return null;17            }18        }).when(mockedList).add("one");19        mockedList.add("one");20    }21}22Related Posts: Mockito : How to use doCallRealMethod() method23Mockito : How to use doThrow() method24Mockito : How to use doNothing() method25Mockito : How to use doReturn() method26Mockito : How to use doReturn() method with multiple…27Mockito : How to use doThrow() method with multiple…28Mockito : How to use doNothing() method with multiple…doAnswer
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.Mockito;5import org.mockito.invocation.InvocationOnMock;6import org.mockito.runners.MockitoJUnitRunner;7import org.mockito.stubbing.Answer;8import static org.junit.Assert.*;9@RunWith(MockitoJUnitRunner.class)10public class 1 {11	public void test() {12		Example a = Mockito.mock(Example.class);13		when(a.get()).thenReturn("1");14		doThrow(NullPointerException.class).when(a).get();15		when(a.get()).thenThrow(NullPointerException.class);16		doAnswer(new Answer() {17			public Object answer(InvocationOnMock invocation) throws Throwable {18				return "Answer";19			}20		}).when(a).get();21		when(a.get()).thenAnswer(new Answer() {22			public Object answer(InvocationOnMock invocation) throws Throwable {23				return "Answer";24			}25		});26		doAnswer(new Answer() {27			public Object answer(InvocationOnMock invocation) throws Throwable {28				return "Answer";29			}30		}).when(a).get();31		when(a.get()).thenAnswer(new Answer() {32			public Object answer(InvocationOnMock invocation) throws Throwable {33				return "Answer";34			}35		});36		doAnswer(new Answer() {37			public Object answer(InvocationOnMock invocation) throws Throwable {38				return "Answer";39			}40		}).when(a).get();41		when(a.get()).thenAnswer(new Answer() {42			public Object answer(InvocationOnMock invocation) throws Throwable {43				return "Answer";44			}45		});46		doAnswer(new Answer() {47			public Object answer(InvocationOnMock invocation) throws Throwable {48				return "Answer";49			}doAnswer
Using AI Code Generation
1package com.automationrhapsody.mockito;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.Mock;5import org.mockito.runners.MockitoJUnitRunner;6import java.util.LinkedList;7import java.util.List;8import static org.mockito.Mockito.doAnswer;9import static org.mockito.Mockito.verify;10@RunWith(MockitoJUnitRunner.class)11public class DoAnswerTest {12    private List mockedList;13    public void testDoAnswer() {14        doAnswer(invocation -> {15            Object arg0 = invocation.getArguments()[0];16            System.out.println("called with arguments: " + arg0);17            return null;18        }).when(mockedList).add("one");19        mockedList.add("one");20        mockedList.add("two");21        verify(mockedList).add("one");22    }23}245. doAnswer() with an Answer25package com.automationrhapsody.mockito;26import org.junit.Test;27import org.junit.runner.RunWith;28import org.mockito.Mock;29import org.mockito.invocation.InvocationOnMock;30import org.mockito.runners.MockitoJUnitRunner;31import org.mockito.stubbing.Answer;32import java.util.LinkedList;33import java.util.List;34import static org.mockito.Mockito.doAnswer;35import static org.mockito.Mockito.verify;36@RunWith(MockitoJUnitRunner.class)37public class DoAnswerTest {38    private List mockedList;39    public void testDoAnswer() {40        doAnswer(new Answer() {41            public Object answer(InvocationOnMock invocation) {42                Object arg0 = invocation.getArguments()[0];43                System.out.println("called with arguments: " + arg0);44                return null;45            }46        }).when(mockedList).add("one");47        mockedList.add("one");48        mockedList.add("two");49        verify(mockedList).add("one");50    }51}526. doAnswer() with a Lambda ExpressiondoAnswer
Using AI Code Generation
1package com.automationrhapsody.mockito;2import static org.mockito.Mockito.*;3import org.junit.Test;4import org.mockito.invocation.InvocationOnMock;5import org.mockito.stubbing.Answer;6public class DoAnswerTest {7    public void testDoAnswer() {8        Interface1 mock = mock(Interface1.class);9        when(mock.method1(anyInt())).thenAnswer(new Answer() {10            public Object answer(InvocationOnMock invocation) {11                Object[] args = invocation.getArguments();12                Object mock = invocation.getMock();13                return "called with arguments: " + args;14            }15        });16        System.out.println(mock.method1(1));17    }18}19interface Interface1 {20    String method1(int i);21}22package com.automationrhapsody.mockito;23import static org.mockito.Mockito.*;24import org.junit.Test;25import org.mockito.invocation.InvocationOnMock;26import org.mockito.stubbing.Answer;27public class DoAnswerTest {28    public void testDoAnswer() {29        Interface1 mock = mock(Interface1.class);30        doAnswer(new Answer() {31            public Object answer(InvocationOnMock invocation) {32                Object[] args = invocation.getArguments();33                Object mock = invocation.getMock();34                System.out.println("called with arguments: " + args);35                return null;36            }37        }).when(mock).method1(anyInt());38        mock.method1(1);39    }40}41interface Interface1 {42    void method1(int i);43}44Mockito doThrow method is used to stub a method to throw an exception. This is similar to doReturn() method. The difference is that doReturn() method can be used to stub a method with a return valuedoAnswer
Using AI Code Generation
1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5import java.util.*;6import java.io.*;7public class 1 {8public static void main(String[] args) {9List mockList = mock(ArrayList.class);10doAnswer(new Answer() {11public Object answer(InvocationOnMock invocation) throws Throwable {12Object[] args = invocation.getArguments();13Object mock = invocation.getMock();14System.out.println("called with arguments: " + Arrays.toString(args));15return null;16}17}).when(mockList).add(1);18mockList.add(1);19}20}21import org.mockito.Mockito;22import static org.mockito.Mockito.*;23import org.mockito.invocation.InvocationOnMock;24import org.mockito.stubbing.Answer;25import java.util.*;26import java.io.*;27public class 2 {28public static void main(String[] args) {29List mockList = mock(ArrayList.class);30doAnswer(new Answer() {31public Object answer(InvocationOnMock invocation) throws Throwable {32Object[] args = invocation.getArguments();33Object mock = invocation.getMock();34System.out.println("called with arguments: " + Arrays.toString(args));35return null;36}37}).when(mockList).add(1);38mockList.add(1);39}40}41import org.mockito.Mockito;42import static org.mockito.Mockito.*;43import org.mockito.invocation.InvocationOnMock;44import org.mockito.stubbing.Answer;45import java.util.*;46import java.io.*;47public class 3 {48public static void main(String[] args) {49List mockList = mock(ArrayList.class);50doAnswer(new Answer() {51public Object answer(InvocationOnMock invocation) throws Throwable {doAnswer
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4public class MockitoDoAnswerExample {5   public static void main(String[] args) {6      MyClass test = Mockito.mock(MyClass.class);7      Mockito.doAnswer(new Answer() {8         public Object answer(InvocationOnMock invocation) {9            Object[] args = invocation.getArguments();10            Object mock = invocation.getMock();11            return "called with arguments: " + args;12         }13      }).when(test).simpleMethod(Mockito.anyInt());14      System.out.println(test.simpleMethod(100));15   }16}17Next Topic Mockito doNothing() and doThrow() examplesdoAnswer
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4public class 1 {5    public static void main(String[] args) {6        MyInterface myInterface = Mockito.mock(MyInterface.class);7        Answer answer = new Answer() {8            public Object answer(InvocationOnMock invocation) throws Throwable {9                Object[] args = invocation.getArguments();10                String methodName = invocation.getMethod().getName();11                Class returnType = invocation.getMethod().getReturnType();12                if (methodName.equals("doSomething") && returnType == int.class) {13                    return 20;14                }15                return null;16            }17        };18        Mockito.doAnswer(answer).when(myInterface).doSomething();19        int result = myInterface.doSomething();20        System.out.println(result);21    }22}doAnswer
Using AI Code Generation
1package org.mockito;2import static org.mockito.Mockito.*;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5public class 1 {6   public static void main(String[] args) {7      List mockedList = mock(List.class);8      when(mockedList.get(anyInt())).thenAnswer(new Answer() {9         public Object answer(InvocationOnMock invocation) {10            Object[] args = invocation.getArguments();11            Object mock = invocation.getMock();12            return "called with arguments: " + args;13         }14      });15      System.out.println(mockedList.get(0));16      verify(mockedList).get(anyInt());17   }18}doAnswer
Using AI Code Generation
1import org.mockito.invocation.InvocationOnMock;2import org.mockito.stubbing.Answer;3public class MockingDoAnswer {4public static void main(String[] args) {5CalculatorService calcService = mock(CalculatorService.class);6when(calcService.add(10.0,20.0)).thenReturn(30.00);7when(calcService.subtract(20.0,10.0)).thenReturn(10.00);8when(calcService.multiply(10.0,20.0)).thenReturn(200.00);9when(calcService.divide(20.0,10.0)).thenReturn(2.00);10doAnswer(new Answer<Double>() {11public Double answer(InvocationOnMock invocation) {12Object[] args = invocation.getArguments();13Object mock = invocation.getMock();14return 10.0;15}16}).when(calcService).add(10.0,20.0);17doAnswer(new Answer<Double>() {18public Double answer(InvocationOnMock invocation) {19Object[] args = invocation.getArguments();20Object mock = invocation.getMock();21return 10.0;22}23}).when(calcService).subtract(20.0,10.0);24doAnswer(new Answer<Double>() {25public Double answer(InvocationOnMock invocation) {26Object[] args = invocation.getArguments();27Object mock = invocation.getMock();28return 200.0;29}30}).when(calcService).multiply(10.0,20.0);31doAnswer(new Answer<Double>() {32public Double answer(InvocationOnMock invocation) {33Object[] args = invocation.getArguments();34Object mock = invocation.getMock();35return 2.0;36}37}).when(calcService).divide(20.0,10.0);38assertEquals(calcService.add(10.0,20.0),10.0,039@RunWith(MockitoJUnitRunner.class)40public class DoAnswerTest {41    private List mockedList;42    public void testDoAnswer() {43        doAnswer(new Answer() {44            public Object answer(InvocationOnMock invocation) {45                Object arg0 = invocation.getArguments()[0];46                System.out.println("called with arguments: " + arg0);47                return null;48            }49        }).when(mockedList).add("one");50        mockedList.add("one");51        mockedList.add("two");52        verify(mockedList).add("one");53    }54}556. doAnswer() with a Lambda ExpressiondoAnswer
Using AI Code Generation
1import org.mockito.invocation.InvocationOnMock;2import org.mockito.stubbing.Answer;3public class MockingDoAnswer {4public static void main(String[] args) {5CalculatorService calcService = mock(CalculatorService.clfss);6when(calcService.add(10.0,20.0)).thenReturn(30.00);7when(calcService.subtract(20.0,10.0)).thenReturn(10.00);8when(calcService.multiply(10.0,20.0)).thenReturn(200.00);9when(calcService.divide(20.0,10.0)).thenReturn(2.00);10doAnswer(new Answer<Double>() {11public Double answer(InvocationOnMock invocation) {12Object[] args = invocation.getArguments();13Object mock = invocation.getMock();14return 10.0;15}16}).when(calcService).add(10.0,20.0);17doAnswer(new Answer<Double>() {18public Double answer(InvocationOnMock invocation) {19Object[] args = invocation.getArguments();20Object mock = invocation.getMock();21return 10.0;22}23}).when(calcService).subtract(20.0,10.0);24doAnswer(new Answer<Double>() {25public Double answer(InvocationOnMock invocation) {26Object[] args = invocation.getArguments();27Object mock = invocation.getMock();28return 200.0;29}30}).when(calcService).multiply(10.0,20.0);31doAnswer(new Answer<Double>() {32public Double answer(InvocationOnMock invocation) {33Object[] args = invocation.getArguments();34Object mock = invocation.getMock();35return 2.0;36}37}).when(calcService).divide(20.0,10.0);38assertEquals(calcService.add(10.0,20.0),10.0,0rg.mockito.Mockito class39package com.automationrhapsody.mockito;40import static org.mockito.Mockito.*;41import org.junit.Test;42import org.mockito.invocation.InvocationOnMock;43import org.mockito.stubbing.Answer;44public class DoAnswerTest {45    public void testDoAnswer() {46        Interface1 mock = mock(Interface1.class);47        when(mock.method1(anyInt())).thenAnswer(new Answer() {48            public Object answer(InvocationOnMock invocation) {49                Object[] args = invocation.getArguments();50                Object mock = invocation.getMock();51                return "called with arguments: " + args;52            }53        });54        System.out.println(mock.method1(1));55    }56}57interface Interface1 {58    String method1(int i);59}60package com.automationrhapsody.mockito;61import static org.mockito.Mockito.*;62import org.junit.Test;63import org.mockito.invocation.InvocationOnMock;64import org.mockito.stubbing.Answer;65public class DoAnswerTest {66    public void testDoAnswer() {67        Interface1 mock = mock(Interface1.class);68        doAnswer(new Answer() {69            public Object answer(InvocationOnMock invocation) {70                Object[] args = invocation.getArguments();71                Object mock = invocation.getMock();72                System.out.println("called with arguments: " + args);73                return null;74            }75        }).when(mock).method1(anyInt());76        mock.method1(1);77    }78}79interface Interface1 {80    void method1(int i);81}82Mockito doThrow method is used to stub a method to throw an exception. This is similar to doReturn() method. The difference is that doReturn() method can be used to stub a method with a return valuedoAnswer
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4public class MockitoDoAnswerExample {5   public static void main(String[] args) {6      MyClass test = Mockito.mock(MyClass.class);7      Mockito.doAnswer(new Answer() {8         public Object answer(InvocationOnMock invocation) {9            Object[] args = invocation.getArguments();10            Object mock = invocation.getMock();11            return "called with arguments: " + args;12         }13      }).when(test).simpleMethod(Mockito.anyInt());14      System.out.println(test.simpleMethod(100));15   }16}17Next Topic Mockito doNothing() and doThrow() examplesdoAnswer
Using AI Code Generation
1package org.mockito;2import static org.mockito.Mockito.*;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5public class 1 {6   public static void main(String[] args) {7      List mockedList = mock(List.class);8      when(mockedList.get(anyInt())).thenAnswer(new Answer() {9         public Object answer(InvocationOnMock invocation) {10            Object[] args = invocation.getArguments();11            Object mock = invocation.getMock();12            return "called with arguments: " + args;13         }14      });15      System.out.println(mockedList.get(0));16      verify(mockedList).get(anyInt());17   }18}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
