How to use method of org.mockito.Mockito class

Best Mockito code snippet using org.mockito.Mockito.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package com.baeldung.mockito.mocksettings;
2
3import static org.mockito.Answers.RETURNS_SMART_NULLS;
4import static org.junit.Assert.assertEquals;
5import static org.mockito.Answers.CALLS_REAL_METHODS;
6import static org.mockito.Mockito.mock;
7import static org.mockito.Mockito.verify;
8import static org.mockito.Mockito.when;
9import static org.mockito.Mockito.withSettings;
10
11import org.junit.Test;
12import org.junit.runner.RunWith;
13import org.mockito.exceptions.verification.SmartNullPointerException;
14import org.mockito.junit.MockitoJUnitRunner;
15
16import com.baeldung.mockito.fluentapi.Pizza;
17import com.baeldung.mockito.fluentapi.PizzaService;
18
19@RunWith(MockitoJUnitRunner.class)
20public class MockSettingsUnitTest {
21
22    @Test(expected = SmartNullPointerException.class)
23    public void whenServiceMockedWithSmartNulls_thenExceptionHasExtraInfo() {
24        PizzaService service = mock(PizzaService.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS));
25        Pizza pizza = service.orderHouseSpecial();
26        pizza.getSize();
27    }
28
29    @Test
30    public void whenServiceMockedWithNameAndVerboseLogging_thenLogsMethodInvocations() {
31        PizzaService service = mock(PizzaService.class, withSettings().name("pizzaServiceMock")
32            .verboseLogging());
33
34        Pizza pizza = mock(Pizza.class);
35        when(service.orderHouseSpecial()).thenReturn(pizza);
36
37        service.orderHouseSpecial();
38
39        verify(service).orderHouseSpecial();
40    }
41
42    @Test
43    public void whenServiceMockedWithExtraInterfaces_thenConstructorSuccess() {
44        SpecialInterface specialMock = mock(SpecialInterface.class, withSettings().extraInterfaces(Runnable.class));
45        new SimpleService(specialMock);
46    }
47
48    @Test
49    public void whenMockSetupWithConstructor_thenConstructorIsInvoked() {
50        AbstractCoffee coffeeSpy = mock(AbstractCoffee.class, withSettings().useConstructor("espresso")
51            .defaultAnswer(CALLS_REAL_METHODS));
52
53        assertEquals("Coffee name: ", "espresso", coffeeSpy.getName());
54    }
55
56}
57
Full Screen
copy
1/*
2 * Copyright (c) 2007 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockitousage.basicapi;
6
7import org.junit.Test;
8import org.mockito.exceptions.base.MockitoException;
9import org.mockitousage.IMethods;
10import org.mockitoutil.TestBase;
11
12import static org.hamcrest.CoreMatchers.is;
13import static org.mockito.Mockito.*;
14
15public class MockingMultipleInterfacesTest extends TestBase {
16
17    class Foo {
18    }
19
20    interface IFoo {
21    }
22
23    interface IBar {
24    }
25
26    @Test
27    public void shouldAllowMultipleInterfaces() {
28        //when
29        Foo mock = mock(Foo.class, withSettings().extraInterfaces(IFoo.class, IBar.class));
30
31        //then
32        assertThat(mock, is(IFoo.class));
33        assertThat(mock, is(IBar.class));
34    }
35
36    @Test
37    public void shouldScreamWhenNullPassedInsteadOfAnInterface() {
38        try {
39            //when
40            mock(Foo.class, withSettings().extraInterfaces(IFoo.class, null));
41            fail();
42        } catch (MockitoException e) {
43            //then
44            assertContains("extraInterfaces() does not accept null parameters", e.getMessage());
45        }
46    }
47
48    @Test
49    public void shouldScreamWhenNoArgsPassed() {
50        try {
51            //when
52            mock(Foo.class, withSettings().extraInterfaces());
53            fail();
54        } catch (MockitoException e) {
55            //then
56            assertContains("extraInterfaces() requires at least one interface", e.getMessage());
57        }
58    }
59
60    @Test
61    public void shouldScreamWhenNullPassedInsteadOfAnArray() {
62        try {
63            //when
64            mock(Foo.class, withSettings().extraInterfaces((Class[]) null));
65            fail();
66        } catch (MockitoException e) {
67            //then
68            assertContains("extraInterfaces() requires at least one interface", e.getMessage());
69        }
70    }
71
72    @Test
73    public void shouldScreamWhenNonInterfacePassed() {
74        try {
75            //when
76            mock(Foo.class, withSettings().extraInterfaces(Foo.class));
77            fail();
78        } catch (MockitoException e) {
79            //then
80            assertContains("Foo which is not an interface", e.getMessage());
81        }
82    }
83
84    @Test
85    public void shouldScreamWhenTheSameInterfacesPassed() {
86        try {
87            //when
88            mock(IMethods.class, withSettings().extraInterfaces(IMethods.class));
89            fail();
90        } catch (MockitoException e) {
91            //then
92            assertContains("You mocked following type: IMethods", e.getMessage());
93        }
94    }
95}
Full Screen
copy
1/*
2 * Copyright (c) 2007 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockito.internal.creation;
6
7import org.junit.Before;
8import org.junit.Test;
9import org.mockito.Mockito;
10import org.mockito.cglib.proxy.MethodProxy;
11import org.mockito.internal.MockitoInvocationHandler;
12import org.mockito.internal.creation.cglib.CGLIBHacker;
13import org.mockito.internal.invocation.Invocation;
14import org.mockito.internal.invocation.InvocationBuilder;
15import org.mockito.internal.invocation.MockitoMethod;
16import org.mockito.internal.invocation.SerializableMethod;
17import org.mockitousage.MethodsImpl;
18import org.mockitoutil.TestBase;
19
20import java.io.ByteArrayOutputStream;
21import java.io.ObjectOutputStream;
22import java.lang.reflect.Method;
23
24import static org.hamcrest.core.IsInstanceOf.any;
25import static org.hamcrest.core.IsInstanceOf.instanceOf;
26import static org.mockito.Matchers.*;
27import static org.mockito.Mockito.*;
28
29public class MethodInterceptorFilterTest extends TestBase {
30
31    MockitoInvocationHandler handler = Mockito.mock(MockitoInvocationHandler.class);
32    MethodInterceptorFilter filter = new MethodInterceptorFilter(handler, (MockSettingsImpl) withSettings());
33
34    @Before
35    public void setUp() {
36        filter.cglibHacker = Mockito.mock(CGLIBHacker.class);
37    }
38
39    @Test
40    public void shouldBeSerializable() throws Exception {
41        new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(new MethodInterceptorFilter(null, null));
42    }
43
44    @Test
45    public void shouldProvideOwnImplementationOfHashCode() throws Throwable {
46        //when
47        Object ret = filter.intercept(new MethodsImpl(), MethodsImpl.class.getMethod("hashCode"), new Object[0], null);
48
49        //then
50        assertTrue((Integer) ret != 0);
51        Mockito.verify(handler, never()).handle(any(Invocation.class));
52    }
53
54    @Test
55    public void shouldProvideOwnImplementationOfEquals() throws Throwable {
56        //when
57        MethodsImpl proxy = new MethodsImpl();
58        Object ret = filter.intercept(proxy, MethodsImpl.class.getMethod("equals", Object.class), new Object[]{proxy}, null);
59
60        //then
61        assertTrue((Boolean) ret);
62        Mockito.verify(handler, never()).handle(any(Invocation.class));
63    }
64
65    //TODO: move to separate factory
66    @Test
67    public void shouldCreateSerializableMethodProxyIfIsSerializableMock() throws Exception {
68        MethodInterceptorFilter filter = new MethodInterceptorFilter(handler, (MockSettingsImpl) withSettings().serializable());
69        MethodProxy methodProxy = MethodProxy.create(String.class, String.class, "", "toString", "toString");
70
71        // when
72        MockitoMethodProxy mockitoMethodProxy = filter.createMockitoMethodProxy(methodProxy);
73
74        // then
75        assertThat(mockitoMethodProxy, instanceOf(SerializableMockitoMethodProxy.class));
76    }
77
78    @Test
79    public void shouldCreateNONSerializableMethodProxyIfIsNotSerializableMock() throws Exception {
80        MethodInterceptorFilter filter = new MethodInterceptorFilter(handler, (MockSettingsImpl) withSettings());
81        MethodProxy methodProxy = MethodProxy.create(String.class, String.class, "", "toString", "toString");
82
83        // when
84        MockitoMethodProxy mockitoMethodProxy = filter.createMockitoMethodProxy(methodProxy);
85
86        // then
87        assertThat(mockitoMethodProxy, instanceOf(DelegatingMockitoMethodProxy.class));
88    }
89
90    @Test
91    public void shouldCreateSerializableMethodIfIsSerializableMock() throws Exception {
92        MethodInterceptorFilter filter = new MethodInterceptorFilter(handler, (MockSettingsImpl) withSettings().serializable());
93        Method method = new InvocationBuilder().toInvocation().getMethod();
94
95        // when
96        MockitoMethod mockitoMethod = filter.createMockitoMethod(method);
97
98        // then
99        assertThat(mockitoMethod, instanceOf(SerializableMethod.class));
100    }
101
102    @Test
103    public void shouldCreateJustDelegatingMethodIfIsNotSerializableMock() throws Exception {
104        MethodInterceptorFilter filter = new MethodInterceptorFilter(handler, (MockSettingsImpl) withSettings());
105        Method method = new InvocationBuilder().toInvocation().getMethod();
106
107        // when
108        MockitoMethod mockitoMethod = filter.createMockitoMethod(method);
109
110        // then
111        assertThat(mockitoMethod, instanceOf(DelegatingMethod.class));
112    }
113}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)