Best Mockito code snippet using org.mockito.Mockito.lenient
UnnecessaryStubbingException in Mockito?By default, Mockito 3.0+ enable strict strubbing. Strict stubbing ensures that redundant test code is minimal by raising an exception - UnnecessaryStubbingException, when an unused stub is declared or a stub is declared twice.
1Mockito.when(mockObject.someMethod()).thenReturn(1); 2Mockito.when(mockObject.someMethod()).thenReturn(2);
In the code above, the someMethod is stubbed twice, which is unnecessary and would trigger the UnnecessaryStubbingException. To avoid this, you should only stub a method once and only if it's necessary for your test case.
1MyClass mockObject = Mockito.mock(MyClass.class); 2Mockito.when(mockObject.someMethod()).thenReturn(1);
In this code, the method someMethod is stubbed, but it's not called in the test case. This results in an unused stub, and causes the exception to be raised.
To bypass strict stubbing, stubs can be configured as lenient which will not raise the exception. These stubs won't be checked for potential stubbing problems, such as the unnecessary stubbing.
1MyClass mockObject = Mockito.mock(MyClass.class, Mockito.RETURNS_SMART_NULLS); 2Mockito.lenient().when(mockObject.someMethod()).thenReturn(1);
In this example, mockObject is created as a lenient mock. This bypasses the strict stubbing checks.
Keep in mind that lenient mocks should be used with caution, as they can hide potential problems in your test code. It's best to use strict mocks (the default behavior in Mockito) and only use lenient mocks if necessary.
Here are code snippets that can help you understand more how developers are using
Source:StrictnessPerStubbingTest.java  
...4 */5package org.mockitousage.strictness;6import static org.assertj.core.api.Assertions.assertThatThrownBy;7import static org.junit.Assert.assertEquals;8import static org.mockito.Mockito.lenient;9import static org.mockito.Mockito.mock;10import static org.mockito.Mockito.spy;11import static org.mockito.Mockito.verifyNoMoreInteractions;12import static org.mockito.Mockito.when;13import org.assertj.core.api.ThrowableAssert;14import org.junit.After;15import org.junit.Before;16import org.junit.Test;17import org.mockito.AdditionalAnswers;18import org.mockito.Mock;19import org.mockito.Mockito;20import org.mockito.MockitoSession;21import org.mockito.exceptions.misusing.PotentialStubbingProblem;22import org.mockito.exceptions.misusing.UnnecessaryStubbingException;23import org.mockito.exceptions.verification.NoInteractionsWanted;24import org.mockito.quality.Strictness;25import org.mockitousage.IMethods;26import org.mockitoutil.TestBase;27public class StrictnessPerStubbingTest {28    MockitoSession mockito;29    @Mock IMethods mock;30    @Before31    public void before() {32        mockito =33                Mockito.mockitoSession()34                        .initMocks(this)35                        .strictness(Strictness.STRICT_STUBS)36                        .startMocking();37    }38    @Test39    public void potential_stubbing_problem() {40        // when41        when(mock.simpleMethod("1")).thenReturn("1");42        lenient().when(mock.differentMethod("2")).thenReturn("2");43        // then on lenient stubbing, we can call it with different argument:44        mock.differentMethod("200");45        // but on strict stubbing, we cannot:46        assertThatThrownBy(47                        new ThrowableAssert.ThrowingCallable() {48                            @Override49                            public void call() throws Throwable {50                                ProductionCode.simpleMethod(mock, "100");51                            }52                        })53                .isInstanceOf(PotentialStubbingProblem.class);54    }55    @Test56    public void doReturn_syntax() {57        // when58        lenient().doReturn("2").doReturn("3").when(mock).simpleMethod(1);59        // then on lenient stubbing, we can call it with different argument:60        mock.simpleMethod(200);61        // and stubbing works, too:62        assertEquals("2", mock.simpleMethod(1));63        assertEquals("3", mock.simpleMethod(1));64    }65    @Test66    public void doReturn_varargs_syntax() {67        // when68        lenient().doReturn("2", "3").when(mock).simpleMethod(1);69        // then on lenient stubbing, we can call it with different argument with no exception:70        mock.simpleMethod(200);71        // and stubbing works, too:72        assertEquals("2", mock.simpleMethod(1));73        assertEquals("3", mock.simpleMethod(1));74    }75    @Test76    public void doThrow_syntax() {77        // when78        lenient()79                .doThrow(IllegalArgumentException.class)80                .doThrow(IllegalStateException.class)81                .when(mock)82                .simpleMethod(1);83        // then on lenient stubbing, we can call it with different argument with no exception:84        mock.simpleMethod(200);85        // and stubbing works, too:86        assertThatThrownBy(87                        new ThrowableAssert.ThrowingCallable() {88                            public void call() throws Throwable {89                                mock.simpleMethod(1);90                            }91                        })92                .isInstanceOf(IllegalArgumentException.class);93        // testing consecutive call:94        assertThatThrownBy(95                        new ThrowableAssert.ThrowingCallable() {96                            public void call() throws Throwable {97                                mock.simpleMethod(1);98                            }99                        })100                .isInstanceOf(IllegalStateException.class);101    }102    @Test103    public void doThrow_vararg_syntax() {104        // when105        lenient()106                .doThrow(IllegalArgumentException.class, IllegalStateException.class)107                .when(mock)108                .simpleMethod(1);109        // then on lenient stubbing, we can call it with different argument with no exception:110        mock.simpleMethod(200);111        // and stubbing works, too:112        assertThatThrownBy(113                        new ThrowableAssert.ThrowingCallable() {114                            public void call() throws Throwable {115                                mock.simpleMethod(1);116                            }117                        })118                .isInstanceOf(IllegalArgumentException.class);119        // testing consecutive call:120        assertThatThrownBy(121                        new ThrowableAssert.ThrowingCallable() {122                            public void call() throws Throwable {123                                mock.simpleMethod(1);124                            }125                        })126                .isInstanceOf(IllegalStateException.class);127    }128    @Test129    public void doThrow_instance_vararg_syntax() {130        // when131        lenient()132                .doThrow(new IllegalArgumentException(), new IllegalStateException())133                .when(mock)134                .simpleMethod(1);135        // then on lenient stubbing, we can call it with different argument with no exception:136        mock.simpleMethod(200);137        // and stubbing works, too:138        assertThatThrownBy(139                        new ThrowableAssert.ThrowingCallable() {140                            public void call() throws Throwable {141                                mock.simpleMethod(1);142                            }143                        })144                .isInstanceOf(IllegalArgumentException.class);145        // testing consecutive call:146        assertThatThrownBy(147                        new ThrowableAssert.ThrowingCallable() {148                            public void call() throws Throwable {149                                mock.simpleMethod(1);150                            }151                        })152                .isInstanceOf(IllegalStateException.class);153    }154    static class Counter {155        int increment(int x) {156            return x + 1;157        }158        void scream(String message) {159            throw new RuntimeException(message);160        }161    }162    @Test163    public void doCallRealMethod_syntax() {164        // when165        Counter mock = mock(Counter.class);166        lenient().doCallRealMethod().when(mock).increment(1);167        // then no exception and default return value if we call it with different arg:168        assertEquals(0, mock.increment(0));169        // and real method is called when using correct arg:170        assertEquals(2, mock.increment(1));171    }172    @Test173    public void doNothing_syntax() {174        // when175        final Counter spy = spy(Counter.class);176        lenient().doNothing().when(spy).scream("1");177        // then no stubbing exception and real method is called if we call stubbed method with178        // different arg:179        assertThatThrownBy(180                        new ThrowableAssert.ThrowingCallable() {181                            @Override182                            public void call() throws Throwable {183                                spy.scream("2");184                            }185                        })186                .hasMessage("2");187        // and we do nothing when stubbing called with correct arg:188        spy.scream("1");189    }190    @Test191    public void doAnswer_syntax() {192        // when193        lenient().doAnswer(AdditionalAnswers.returnsFirstArg()).when(mock).simpleMethod("1");194        // then on lenient stubbing, we can call it with different argument:195        mock.simpleMethod("200");196        // and stubbing works, too:197        assertEquals("1", mock.simpleMethod("1"));198    }199    @Test200    public void unnecessary_stubbing() {201        // when202        when(mock.simpleMethod("1")).thenReturn("1");203        lenient().when(mock.differentMethod("2")).thenReturn("2");204        // then unnecessary stubbing flags method only on the strict stubbing:205        assertThatThrownBy(206                        new ThrowableAssert.ThrowingCallable() {207                            @Override208                            public void call() throws Throwable {209                                mockito.finishMocking();210                            }211                        })212                .isInstanceOf(UnnecessaryStubbingException.class)213                .hasMessageContaining("1. -> ")214                // good enough to prove that we're flagging just one unnecessary stubbing:215                // TODO 792: this assertion is duplicated with StrictnessPerMockTest216                .isNot(TestBase.hasMessageContaining("2. ->"));217    }218    @Test219    public void unnecessary_stubbing_with_doReturn() {220        // when221        lenient().doReturn("2").when(mock).differentMethod("2");222        // then no exception is thrown:223        mockito.finishMocking();224    }225    @Test226    public void verify_no_more_invocations() {227        // when228        when(mock.simpleMethod("1")).thenReturn("1");229        lenient().when(mock.differentMethod("2")).thenReturn("2");230        // and:231        mock.simpleMethod("1");232        mock.differentMethod("200"); // <- different arg233        // then 'verifyNoMoreInteractions' flags the lenient stubbing (called with different arg)234        // and reports it with [?] in the exception message235        assertThatThrownBy(236                        new ThrowableAssert.ThrowingCallable() {237                            @Override238                            public void call() throws Throwable {239                                verifyNoMoreInteractions(mock);240                            }241                        })242                .isInstanceOf(NoInteractionsWanted.class)243                .hasMessageContaining("1. ->")244                .hasMessageContaining("2. [?]->");245        // TODO 792: assertion duplicated with StrictnessPerMockTest246        // and we should use assertions based on content of the exception rather than the string247    }...Source:ProcessInstanceManagementResourceTest.java  
...39import static org.assertj.core.api.Assertions.assertThat;40import static org.mockito.Matchers.any;41import static org.mockito.Matchers.anyString;42import static org.mockito.Mockito.doAnswer;43import static org.mockito.Mockito.lenient;44import static org.mockito.Mockito.mock;45import static org.mockito.Mockito.spy;46import static org.mockito.Mockito.times;47import static org.mockito.Mockito.verify;48import static org.mockito.Mockito.when;49@ExtendWith(MockitoExtension.class)50public class ProcessInstanceManagementResourceTest {51    public static final String MESSAGE = "message";52    public static final String PROCESS_ID = "test";53    public static final String PROCESS_INSTANCE_ID = "xxxxx";54    public static final String NODE_ID = "abc-def";55    private static RuntimeDelegate runtimeDelegate;56    private ResponseBuilder responseBuilder;57    private Processes processes;58    @SuppressWarnings("rawtypes")59    private ProcessInstance processInstance;60    private ProcessError error;61    private Application application;62    private ProcessInstanceManagementResource resource;63    @BeforeAll64    public static void configureEnvironment() {65        runtimeDelegate = mock(RuntimeDelegate.class);66        RuntimeDelegate.setInstance(runtimeDelegate);67    }68    @SuppressWarnings({"rawtypes", "unchecked"})69    @BeforeEach70    public void setup() {71        responseBuilder = mock(ResponseBuilder.class);72        Response response = mock(Response.class);73        when((runtimeDelegate).createResponseBuilder()).thenReturn(responseBuilder);74        lenient().when((responseBuilder).status(any(StatusType.class))).thenReturn(responseBuilder);75        lenient().when((responseBuilder).entity(any())).thenReturn(responseBuilder);76        lenient().when((responseBuilder).build()).thenReturn(response);77        application = mock(Application.class);78        processes = mock(Processes.class);79        Process process = mock(Process.class);80        ProcessInstances instances = mock(ProcessInstances.class);81        processInstance = mock(ProcessInstance.class);82        error = mock(ProcessError.class);83        lenient().when(processes.processById(anyString())).thenReturn(process);84        lenient().when(process.instances()).thenReturn(instances);85        lenient().when(instances.findById(anyString())).thenReturn(Optional.of(processInstance));86        lenient().when(processInstance.error()).thenReturn(Optional.of(error));87        lenient().when(processInstance.id()).thenReturn("abc-def");88        lenient().when(processInstance.status()).thenReturn(ProcessInstance.STATE_ACTIVE);89        lenient().when(error.failedNodeId()).thenReturn("xxxxx");90        lenient().when(error.errorMessage()).thenReturn("Test error message");91        lenient().when(application.unitOfWorkManager()).thenReturn(new DefaultUnitOfWorkManager(new CollectingUnitOfWorkFactory()));92        resource = spy(new ProcessInstanceManagementResource(processes, application));93    }94    @Test95    public void testGetErrorInfo() {96        Response response = resource.getInstanceInError("test", "xxxxx");97        assertThat(response).isNotNull();98        verify(responseBuilder, times(1)).status((StatusType) Status.OK);99        verify(responseBuilder, times(1)).entity(any());100        verify(processInstance, times(2)).error();101        verify(error, times(0)).retrigger();102        verify(error, times(0)).skip();103        verify(resource).doGetInstanceInError(PROCESS_ID, PROCESS_INSTANCE_ID);104    }105    @Test...Source:DateValidationRulePowerMockTest.java  
...87        Mockito.when(mockSecConfig.getLenientDatesAccepted()).thenReturn(false);88        89        uit = new DateValidationRule(testName.getMethodName(), mockEncoder, testFormat);90        91        //Configuration is lenient=false92        testFormat.setLenient(true);93        Mockito.reset(testFormat, mockSecConfig);94        Assert.assertTrue(testFormat.isLenient());95        96        Mockito.when(mockSecConfig.getLenientDatesAccepted()).thenReturn(false);97        98        uit.setDateFormat(testFormat);99        100        Assert.assertFalse(testFormat.isLenient());101        102        Mockito.verify(mockSecConfig, Mockito.times(1)).getLenientDatesAccepted();103        Mockito.verify(testFormat, Mockito.times(0)).setLenient(true);104        Mockito.verify(testFormat, Mockito.times(1)).setLenient(false);105        106        PowerMockito.verifyStatic(ObjFactory.class, VerificationModeFactory.times(2));107        ObjFactory.make(ArgumentMatchers.anyString(), ArgumentMatchers.eq("SecurityConfiguration"));108        109        PowerMockito.verifyNoMoreInteractions(ObjFactory.class);110    }111    112    @Test113    public void testSetDateFormatLenientTrueFromSetter() {114        Mockito.when(mockSecConfig.getLenientDatesAccepted()).thenReturn(true);115        116        uit = new DateValidationRule(testName.getMethodName(), mockEncoder, testFormat);117        118        //Configuration is lenient=true119        testFormat.setLenient(false);120        Mockito.reset(testFormat, mockSecConfig);121        Assert.assertFalse(testFormat.isLenient());122        123        Mockito.when(mockSecConfig.getLenientDatesAccepted()).thenReturn(true);124        125        uit.setDateFormat(testFormat);126        127        Assert.assertTrue(testFormat.isLenient());128        129        Mockito.verify(mockSecConfig, Mockito.times(1)).getLenientDatesAccepted();130        Mockito.verify(testFormat, Mockito.times(1)).setLenient(true);131        Mockito.verify(testFormat, Mockito.times(0)).setLenient(false);132        ...Source:StrictnessPerMockTest.java  
...28// TODO 792 also move other Strictness tests to this package (unless they already have good package)29public class StrictnessPerMockTest {30    MockitoSession mockito;31    @Mock IMethods strictStubsMock;32    IMethods lenientMock;33    @Before34    public void before() {35        mockito =36                Mockito.mockitoSession()37                        .initMocks(this)38                        .strictness(Strictness.STRICT_STUBS)39                        .startMocking();40        assertNull(lenientMock);41        lenientMock = mock(IMethods.class, withSettings().lenient());42    }43    @Test44    public void knows_if_mock_is_lenient() {45        assertTrue(mockingDetails(lenientMock).getMockCreationSettings().isLenient());46        assertFalse(mockingDetails(strictStubsMock).getMockCreationSettings().isLenient());47    }48    @Test49    public void potential_stubbing_problem() {50        // when51        given(lenientMock.simpleMethod(100)).willReturn("100");52        given(strictStubsMock.simpleMethod(100)).willReturn("100");53        // then on lenient mock (created by hand), we can call the stubbed method with different54        // arg:55        lenientMock.simpleMethod(200);56        // and on strict stub mock (created by session), we cannot call stubbed method with57        // different arg:58        Assertions.assertThatThrownBy(59                        new ThrowableAssert.ThrowingCallable() {60                            public void call() throws Throwable {61                                ProductionCode.simpleMethod(strictStubsMock, 200);62                            }63                        })64                .isInstanceOf(PotentialStubbingProblem.class);65    }66    @Test67    public void unnecessary_stubbing() {68        // when69        given(lenientMock.simpleMethod(100)).willReturn("100");70        given(strictStubsMock.simpleMethod(100)).willReturn("100");71        // then unnecessary stubbing flags method only on the strict stub mock:72        Assertions.assertThatThrownBy(73                        new ThrowableAssert.ThrowingCallable() {74                            @Override75                            public void call() throws Throwable {76                                mockito.finishMocking();77                            }78                        })79                .isInstanceOf(UnnecessaryStubbingException.class)80                .hasMessageContaining("1. -> ")81                // good enough to prove that we're flagging just one unnecessary stubbing:82                // TODO 792: let's make UnnecessaryStubbingException exception contain the83                // Invocation instance84                // so that we can write clean assertion rather than depending on string85                .isNot(TestBase.hasMessageContaining("2. ->"));86    }87    @Test88    public void verify_no_more_invocations() {89        // when90        given(lenientMock.simpleMethod(100)).willReturn("100");91        given(strictStubsMock.simpleMethod(100)).willReturn("100");92        // and:93        strictStubsMock.simpleMethod(100);94        lenientMock.simpleMethod(100);95        // then 'verifyNoMoreInteractions' ignores strict stub (implicitly verified) but flags the96        // lenient mock97        Assertions.assertThatThrownBy(98                        new ThrowableAssert.ThrowingCallable() {99                            @Override100                            public void call() throws Throwable {101                                verifyNoMoreInteractions(strictStubsMock, lenientMock);102                            }103                        })104                .isInstanceOf(NoInteractionsWanted.class)105                .hasMessageContaining("But found this interaction on mock 'iMethods'")106                // TODO 792: let's make NoInteractionsWanted exception contain the Invocation107                // instances108                // so that we can write clean assertion rather than depending on string109                .hasMessageContaining("Actually, above is the only interaction with this mock");110    }111    @After112    public void after() {113        mockito.finishMocking();114    }115}...Source:StrictnessWhenRuleStrictnessIsUpdatedTest.java  
...3 * This program is made available under the terms of the MIT License.4 */5package org.mockitousage.strictness;6import static org.assertj.core.api.Assertions.assertThatThrownBy;7import static org.mockito.Mockito.lenient;8import static org.mockito.Mockito.mock;9import static org.mockito.Mockito.when;10import static org.mockito.Mockito.withSettings;11import org.assertj.core.api.ThrowableAssert;12import org.junit.Rule;13import org.junit.Test;14import org.mockito.Mock;15import org.mockito.exceptions.misusing.PotentialStubbingProblem;16import org.mockito.junit.MockitoJUnit;17import org.mockito.junit.MockitoRule;18import org.mockito.quality.Strictness;19import org.mockitousage.IMethods;20public class StrictnessWhenRuleStrictnessIsUpdatedTest {21    @Mock IMethods mock;22    @Rule public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.LENIENT);23    @Test24    public void strictness_per_mock() {25        // when26        rule.strictness(Strictness.STRICT_STUBS);27        // then previous mock is strict:28        when(mock.simpleMethod(1)).thenReturn("1");29        assertThatThrownBy(30                        new ThrowableAssert.ThrowingCallable() {31                            public void call() {32                                ProductionCode.simpleMethod(mock, 2);33                            }34                        })35                .isInstanceOf(PotentialStubbingProblem.class);36        // but the new mock is lenient, even though the rule is not:37        final IMethods lenientMock = mock(IMethods.class, withSettings().lenient());38        when(lenientMock.simpleMethod(1)).thenReturn("1");39        lenientMock.simpleMethod(100);40    }41    @Test42    public void strictness_per_stubbing() {43        // when44        rule.strictness(Strictness.STRICT_STUBS);45        // then previous mock is strict:46        when(mock.simpleMethod(1)).thenReturn("1");47        assertThatThrownBy(48                        new ThrowableAssert.ThrowingCallable() {49                            public void call() {50                                ProductionCode.simpleMethod(mock, 2);51                            }52                        })53                .isInstanceOf(PotentialStubbingProblem.class);54        // but the new mock is lenient, even though the rule is not:55        lenient().when(mock.simpleMethod(1)).thenReturn("1");56        mock.simpleMethod(100);57    }58}Source:MutableStrictJUnitTestRuleTest.java  
...23        // then24        JUnitResultAssert.assertThat(result).succeeds(1).fails(1, RuntimeException.class);25    }26    @Test27    public void rule_can_be_changed_to_lenient() throws Throwable {28        // when29        Result result = runner.run(StrictByDefault.class);30        // then31        JUnitResultAssert.assertThat(result).succeeds(1).fails(1, RuntimeException.class);32    }33    public static class LenientByDefault {34        @Rule35        public MockitoTestRule mockito = MockitoJUnit.testRule(this).strictness(Strictness.LENIENT);36        @Mock IMethods mock;37        @Test38        public void unused_stub() throws Throwable {39            when(mock.simpleMethod()).thenReturn("1");40        }41        @Test42        public void unused_stub_with_strictness() throws Throwable {43            // making Mockito strict only for this test method44            mockito.strictness(Strictness.STRICT_STUBS);45            when(mock.simpleMethod()).thenReturn("1");46        }47    }48    public static class StrictByDefault {49        @Rule50        public MockitoTestRule mockito =51                MockitoJUnit.testRule(this).strictness(Strictness.STRICT_STUBS);52        @Mock IMethods mock;53        @Test54        public void unused_stub() throws Throwable {55            when(mock.simpleMethod()).thenReturn("1");56        }57        @Test58        public void unused_stub_with_lenient() throws Throwable {59            // making Mockito lenient only for this test method60            mockito.strictness(Strictness.LENIENT);61            when(mock.simpleMethod()).thenReturn("1");62        }63    }64}...Source:MutableStrictJUnitRuleTest.java  
...23        // then24        JUnitResultAssert.assertThat(result).succeeds(1).fails(1, RuntimeException.class);25    }26    @Test27    public void rule_can_be_changed_to_lenient() throws Throwable {28        // when29        Result result = runner.run(StrictByDefault.class);30        // then31        JUnitResultAssert.assertThat(result).succeeds(1).fails(1, RuntimeException.class);32    }33    public static class LenientByDefault {34        @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.LENIENT);35        @Mock IMethods mock;36        @Test37        public void unused_stub() throws Throwable {38            when(mock.simpleMethod()).thenReturn("1");39        }40        @Test41        public void unused_stub_with_strictness() throws Throwable {42            // making Mockito strict only for this test method43            mockito.strictness(Strictness.STRICT_STUBS);44            when(mock.simpleMethod()).thenReturn("1");45        }46    }47    public static class StrictByDefault {48        @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);49        @Mock IMethods mock;50        @Test51        public void unused_stub() throws Throwable {52            when(mock.simpleMethod()).thenReturn("1");53        }54        @Test55        public void unused_stub_with_lenient() throws Throwable {56            // making Mockito lenient only for this test method57            mockito.strictness(Strictness.LENIENT);58            when(mock.simpleMethod()).thenReturn("1");59        }60    }61}...Source:LenientMockAnnotationTest.java  
...15import org.mockito.quality.Strictness;16import org.mockitousage.IMethods;17public class LenientMockAnnotationTest {18    public @Rule MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);19    @Mock(lenient = true)20    IMethods lenientMock;21    @Mock IMethods regularMock;22    @Test23    public void mock_is_lenient() {24        when(lenientMock.simpleMethod("1")).thenReturn("1");25        when(regularMock.simpleMethod("2")).thenReturn("2");26        // then lenient mock does not throw:27        ProductionCode.simpleMethod(lenientMock, "3");28        // but regular mock throws:29        Assertions.assertThatThrownBy(30                        new ThrowableAssert.ThrowingCallable() {31                            public void call() {32                                ProductionCode.simpleMethod(regularMock, "4");33                            }34                        })35                .isInstanceOf(PotentialStubbingProblem.class);36    }37}...lenient
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;3import org.mockito.internal.matchers.Any;4import org.mockito.internal.matchers.CapturingMatcher;5import org.mockito.internal.matchers.Equals;6import org.mockito.internal.matchers.InstanceOf;7import org.mockito.internal.matchers.LessThan;8import org.mockito.internal.matchers.LessThanOrEqual;9import org.mockito.internal.matchers.Not;10import org.mockito.internal.matchers.Null;11import org.mockito.internal.matchers.Same;12import org.mockito.internal.matchers.StartsWith;13import org.mockito.internal.progress.ThreadSafeMockingProgress;14import org.mockito.invocation.Invocation;15import org.mockito.invocation.Location;16import org.mockito.invocation.MatchableInvocation;17import org.mockito.invocation.MockHandler;18import org.mockito.invocation.StubInfo;19import org.mockito.listeners.InvocationListener;20import org.mockito.listeners.MethodInvocationReport;21import org.mockito.listeners.StubbingLookupEvent;22import org.mockito.listeners.StubbingLookupListener;23import org.mockito.matchers.CapturesArguments;24import org.mockito.matchers.IArgumentMatcher;25import org.mockito.matchers.Ic;26import org.mockito.matchers.IcMatcher;27import org.mockito.matchers.IcMatcherFactory;28import org.mockito.matchers.IcMatchers;29import org.mockito.matchers.IcMatchersFactory;30import org.mockito.matchers.IcMatchersFactoryImpl;31import org.mockito.matchers.IcMatchersImpl;32import org.mockito.matchers.IcMatchersImplFactory;33import org.mockito.matchers.IcMatchersImplFactoryImpl;34import org.mockito.matchers.IcMatchersImplFactoryImplFactory;35import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImpl;36import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImplFactory;37import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImplFactoryImpl;38import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImplFactoryImplFactory;39import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImplFactoryImplFactoryImpl;40import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImplFactoryImplFactoryImplFactory;41import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImplFactoryImplFactoryImplFactoryImpl;42import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImplFactoryImplFactoryImplFactoryImplFactory;43import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImplFactoryImplFactoryImplFactoryImplFactoryImpl;44import org.mockito.matchers.IcMatchersImplFactoryImplFactoryImplFactoryImplFactoryImplFactorylenient
Using AI Code Generation
1package com.ack.j2se.mockito;2import static org.mockito.Mockito.lenient;3import static org.mockito.Mockito.mock;4import static org.mockito.Mockito.when;5import java.util.List;6public class LenientMethod {7  public static void main( String[] args ) {8    List list = mock( List.class );9    lenient().when( list.get( 0 ) ).thenReturn( "one" );10    System.out.println( list.get( 0 ) );11  }12}lenient
Using AI Code Generation
1import org.mockito.Mockito;2public class 1 {3    public static void main(String[] args) {4        MyClass test = Mockito.mock(MyClass.class);5        Mockito.lenient().when(test.getUniqueId()).thenReturn(43);6        System.out.println(test.getUniqueId());7    }8}lenient
Using AI Code Generation
1import org.mockito.Mockito;2import java.io.*;3import java.util.*;4public class 1 {5   public static void main(String[] args) {6      List mockedList = Mockito.mock(List.class, Mockito.withSettings().lenient());7      mockedList.add("one");8      mockedList.clear();9      System.out.println(mockedList.get(0));10   }11}12import org.mockito.Mockito;13import java.io.*;14import java.util.*;15public class 2 {16   public static void main(String[] args) {17      List mockedList = Mockito.mock(List.class, Mockito.withSettings().lenient());18      mockedList.add("one");19      mockedList.clear();20      System.out.println(mockedList.size());21   }22}23import org.mockito.Mockito;24import java.io.*;25import java.util.*;26public class 3 {27   public static void main(String[] args) {28      List mockedList = Mockito.mock(List.class, Mockito.withSettings().lenient());29      mockedList.add("one");30      mockedList.clear();31      System.out.println(mockedList.get(0));32      System.out.println(mockedList.size());33   }34}35import org.mockito.Mockito;36import java.io.*;37import java.util.*;38public class 4 {39   public static void main(String[] args) {40      List mockedList = Mockito.mock(List.class, Mockito.withSettings().lenient());41      mockedList.add("one");42      mockedList.clear();43      System.out.println(mockedList.get(0));44      System.out.println(mockedList.size());45      System.out.println(mockedList.get(1));46   }47}48import org.mockito.Mockito;49import java.io.*;50import java.util.*;51public class 5 {52   public static void main(String[] args) {53      List mockedList = Mockito.mock(List.class, Mockito.withSettings().lenient());54      mockedList.add("one");55      mockedList.clear();56      System.out.println(mockedList.get(0));57      System.out.println(mockedList.size());lenient
Using AI Code Generation
1import org.mockito.Mockito;2public class Main {3    public static void main(String[] args) {4        MyClass myClass = Mockito.mock(MyClass.class);5        Mockito.lenient().when(myClass.myMethod()).thenReturn("Hello World");6        System.out.println(myClass.myMethod());7    }8}lenient
Using AI Code Generation
1package org.automation;2import org.junit.Before;3import org.junit.Test;4import org.mockito.Mock;5import org.mockito.MockitoAnnotations;6import org.mockito.MockitoAnnotations.Mock;7import static org.mockito.Mockito.*;8import static org.junit.Assert.*;9import java.util.List;10public class TestClass {11    List<String> mockList;12    public void setUp() throws Exception {13        MockitoAnnotations.initMocks(this);14    }15    public void test() {16        mockList.add("one");17        mockList.clear();18        verify(mockList).add("one");19        verify(mockList).clear();20    }21}221) -> at org.automation.TestClass.test(TestClass.java:20)23E.g. then you should use 'verifyNoMoreInteractions()'24	at org.mockito.exceptions.misusing.UnfinishedVerificationException.create(UnfinishedVerificationException.java:28)25	at org.mockito.internal.verification.api.VerificationDataImpl.build(VerificationDataImpl.java:60)26	at org.mockito.internal.verification.api.VerificationDataImpl.<init>(VerificationDataImpl.java:44)27	at org.mockito.internal.verification.api.VerificationDataFactory.create(VerificationDataFactory.java:24)28	at org.mockito.internal.verification.VerificationModeFactory.noMoreInteractions(VerificationModeFactory.java:73)29	at org.mockito.internal.verification.VerificationModeFactory.noMoreInteractions(VerificationModeFactory.java:57)30	at org.mockito.Mockito.verifyNoMoreInteractions(Mockito.java:1410)31	at org.automation.TestClass.test(TestClass.java:20)32package org.automation;33import org.junit.Before;34import org.junit.Test;35import org.mockito.Mock;36import org.mockito.MockitoAnnotations;37import org.mockito.MockitoAnnotations.Mock;38import static org.mockito.Mockito.*;39import static org.junit.Assert.*;40import java.util.List;41public class TestClass {42    List<String> mockList;43    public void setUp() throws Exception {lenient
Using AI Code Generation
1package org.mockito;2import org.mockito.*;3import org.junit.*;4import org.junit.runner.*;5import org.junit.runners.*;6import org.junit.runners.Parameterized.*;7import org.junit.runners.Parameterized.Parameters;8import static org.mockito.Mockito.*;9import static org.junit.Assert.*;10import java.util.*;11@RunWith(Parameterized.class)12public class Test1{13  public static Collection<Object[]> data() {14        return Arrays.asList(new Object[][] {     15                 { 1, 1, 2 }, { 2, 2, 4 }, { 8, 2, 10 }, { 4, 5, 9 }  16           });17    }18    private int fInput1;19    private int fInput2;20    private int fExpected;21    public Test1(int input1, int input2, int expected) {22        fInput1= input1;23        fInput2= input2;24        fExpected= expected;25    }26    public void test() {27        MyClass tester = new MyClass();28        assertEquals(fExpected, tester.add(fInput1, fInput2));29    }30}31class MyClass{32  public int add(int a, int b){33    return a+b;34  }35}lenient
Using AI Code Generation
1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3public class lenientMethod {4    public static void main(String[] args) {5        SomeClass mock = mock(SomeClass.class);6        Mockito.lenient().when(mock.someMethod()).thenReturn("Hello");7        System.out.println(mock.someMethod());8    }9}lenient
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.internal.util.MockUtil;3import static org.mockito.Mockito.*;4public class 1 {5    public static void main(String[] args) {6        ClassA classA = mock(ClassA.class);7        when(classA.methodA()).thenReturn("methodA");8        when(classA.methodB("methodB")).thenReturn("methodB");9        when(classA.methodC("methodC", 1)).thenReturn("methodC");10        when(classA.methodD("methodD", 1, 2)).thenReturn("methodD");11        when(classA.methodE("methodE", 1, 2, 3)).thenReturn("methodE");12        when(classA.methodF("methodF", 1, 2, 3, 4)).thenReturn("methodF");13        when(classA.methodG("methodG", 1, 2, 3, 4, 5)).thenReturn("methodG");14        when(classA.methodH("methodH", 1, 2, 3, 4, 5, 6)).thenReturn("methodH");15        when(classA.methodI("methodI", 1, 2, 3, 4, 5, 6, 7)).thenReturn("methodI");16        when(classA.methodJ("methodJ", 1, 2, 3, 4, 5, 6, 7, 8)).thenReturn("methodJ");17        when(classA.methodK("methodK", 1, 2, 3, 4, 5, 6, 7, 8, 9)).thenReturn("methodK");18        when(classA.methodL("methodL", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).thenReturn("methodLearn 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!!
