How to use InvocationListener class of org.mockito.listeners package

Best Mockito code snippet using org.mockito.listeners.InvocationListener

Run Mockito automation tests on LambdaTest cloud grid

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

copy
1/*
2 * Copyright 2012-2019 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.springframework.boot.test.mock.mockito;
18
19import java.util.List;
20
21import org.mockito.MockSettings;
22import org.mockito.MockingDetails;
23import org.mockito.Mockito;
24import org.mockito.listeners.InvocationListener;
25import org.mockito.listeners.MethodInvocationReport;
26import org.mockito.mock.MockCreationSettings;
27
28import org.springframework.util.Assert;
29
30/**
31 * Reset strategy used on a mock bean. Usually applied to a mock via the
32 * {@link MockBean @MockBean} annotation but can also be directly applied to any mock in
33 * the {@code ApplicationContext} using the static methods.
34 *
35 * @author Phillip Webb
36 * @since 1.4.0
37 * @see ResetMocksTestExecutionListener
38 */
39public enum MockReset {
40
41	/**
42	 * Reset the mock before the test method runs.
43	 */
44	BEFORE,
45
46	/**
47	 * Reset the mock after the test method runs.
48	 */
49	AFTER,
50
51	/**
52	 * Don't reset the mock.
53	 */
54	NONE;
55
56	/**
57	 * Create {@link MockSettings settings} to be used with mocks where reset should occur
58	 * before each test method runs.
59	 * @return mock settings
60	 */
61	public static MockSettings before() {
62		return withSettings(BEFORE);
63	}
64
65	/**
66	 * Create {@link MockSettings settings} to be used with mocks where reset should occur
67	 * after each test method runs.
68	 * @return mock settings
69	 */
70	public static MockSettings after() {
71		return withSettings(AFTER);
72	}
73
74	/**
75	 * Create {@link MockSettings settings} to be used with mocks where a specific reset
76	 * should occur.
77	 * @param reset the reset type
78	 * @return mock settings
79	 */
80	public static MockSettings withSettings(MockReset reset) {
81		return apply(reset, Mockito.withSettings());
82	}
83
84	/**
85	 * Apply {@link MockReset} to existing {@link MockSettings settings}.
86	 * @param reset the reset type
87	 * @param settings the settings
88	 * @return the configured settings
89	 */
90	public static MockSettings apply(MockReset reset, MockSettings settings) {
91		Assert.notNull(settings, "Settings must not be null");
92		if (reset != null && reset != NONE) {
93			settings.invocationListeners(new ResetInvocationListener(reset));
94		}
95		return settings;
96	}
97
98	/**
99	 * Get the {@link MockReset} associated with the given mock.
100	 * @param mock the source mock
101	 * @return the reset type (never {@code null})
102	 */
103	static MockReset get(Object mock) {
104		MockReset reset = MockReset.NONE;
105		MockingDetails mockingDetails = Mockito.mockingDetails(mock);
106		if (mockingDetails.isMock()) {
107			MockCreationSettings<?> settings = mockingDetails.getMockCreationSettings();
108			List<InvocationListener> listeners = settings.getInvocationListeners();
109			for (Object listener : listeners) {
110				if (listener instanceof ResetInvocationListener) {
111					reset = ((ResetInvocationListener) listener).getReset();
112				}
113			}
114		}
115		return reset;
116	}
117
118	/**
119	 * Dummy {@link InvocationListener} used to hold the {@link MockReset} value.
120	 */
121	private static class ResetInvocationListener implements InvocationListener {
122
123		private final MockReset reset;
124
125		ResetInvocationListener(MockReset reset) {
126			this.reset = reset;
127		}
128
129		MockReset getReset() {
130			return this.reset;
131		}
132
133		@Override
134		public void reportInvocation(MethodInvocationReport methodInvocationReport) {
135		}
136
137	}
138
139}
140
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.mockito.MockSettings;
8import org.mockito.exceptions.Reporter;
9import org.mockito.internal.creation.settings.CreationSettings;
10import org.mockito.internal.debugging.VerboseMockInvocationLogger;
11import org.mockito.internal.util.MockCreationValidator;
12import org.mockito.internal.util.MockNameImpl;
13import org.mockito.internal.util.MockitoSpy;
14import org.mockito.listeners.InvocationListener;
15import org.mockito.mock.MockCreationSettings;
16import org.mockito.mock.MockName;
17import org.mockito.stubbing.Answer;
18
19import java.io.Serializable;
20import java.util.*;
21
22import static org.mockito.internal.util.collections.Sets.newSet;
23
24@SuppressWarnings("unchecked")
25public class MockSettingsImpl<T> extends CreationSettings<T> implements MockSettings, MockCreationSettings<T> {
26
27    private static final long serialVersionUID = 4475297236197939568L;
28
29    public MockSettings serializable() {
30        this.serializable = true;
31        return this;
32    }
33
34    public MockSettings extraInterfaces(Class... extraInterfaces) {
35        if (extraInterfaces == null || extraInterfaces.length == 0) {
36            new Reporter().extraInterfacesRequiresAtLeastOneInterface();
37        }
38
39        for (Class i : extraInterfaces) {
40            if (i == null) {
41                new Reporter().extraInterfacesDoesNotAcceptNullParameters();
42            } else if (!i.isInterface()) {
43                new Reporter().extraInterfacesAcceptsOnlyInterfaces(i);
44            }
45        }
46        this.extraInterfaces = newSet(extraInterfaces);
47        return this;
48    }
49
50    public MockName getMockName() {
51        return mockName;
52    }
53
54    public Set<Class> getExtraInterfaces() {
55        return extraInterfaces;
56    }
57
58    public Object getSpiedInstance() {
59        return spiedInstance;
60    }
61
62    public MockSettings name(String name) {
63        this.name = name;
64        return this;
65    }
66
67    public MockSettings spiedInstance(Object spiedInstance) {
68        this.spiedInstance = spiedInstance;
69        return this;
70    }
71
72    public MockSettings defaultAnswer(Answer defaultAnswer) {
73        this.defaultAnswer = defaultAnswer;
74        return this;
75    }
76
77    public Answer<Object> getDefaultAnswer() {
78        return defaultAnswer;
79    }
80
81    public boolean isSerializable() {
82        return serializable;
83    }
84
85	public MockSettings verboseLogging() {
86        if (!invocationListenersContainsType(VerboseMockInvocationLogger.class)) {
87            invocationListeners(new VerboseMockInvocationLogger());
88        }
89        return this;
90	}
91
92    public MockSettings invocationListeners(InvocationListener... listeners) {
93        if (listeners == null || listeners.length == 0) {
94            new Reporter().invocationListenersRequiresAtLeastOneListener();
95        }
96        for (InvocationListener listener : listeners) {
97            if (listener == null) {
98                new Reporter().invocationListenerDoesNotAcceptNullParameters();
99            }
100            this.invocationListeners.add(listener);
101        }
102		return this;
103	}
104
105	private boolean invocationListenersContainsType(Class<?> clazz) {
106		for (InvocationListener listener : invocationListeners) {
107			if (listener.getClass().equals(clazz)) {
108				return true;
109			}
110		}
111		return false;
112	}
113
114    public List<InvocationListener> getInvocationListeners() {
115        return this.invocationListeners;
116    }
117
118    public boolean hasInvocationListeners() {
119        return !invocationListeners.isEmpty();
120    }
121
122    public Class<T> getTypeToMock() {
123        return typeToMock;
124    }
125
126    public MockCreationSettings<T> confirm(Class<T> typeToMock) {
127        return validatedSettings(typeToMock, this);
128    }
129
130    private static <T> CreationSettings<T> validatedSettings(Class<T> typeToMock, CreationSettings<T> source) {
131        MockCreationValidator validator = new MockCreationValidator();
132
133        validator.validateType(typeToMock);
134        validator.validateExtraInterfaces(typeToMock, source.getExtraInterfaces());
135        validator.validateMockedType(typeToMock, source.getSpiedInstance());
136
137        //TODO SF - add this validation and also add missing coverage
138//        validator.validateDelegatedInstance(classToMock, settings.getDelegatedInstance());
139
140        CreationSettings<T> settings = new CreationSettings<T>(source);
141        settings.setMockName(new MockNameImpl(source.getName(), typeToMock));
142        settings.setTypeToMock(typeToMock);
143        settings.setExtraInterfaces(prepareExtraInterfaces(source));
144        return settings;
145    }
146
147    private static Set<Class> prepareExtraInterfaces(CreationSettings settings) {
148        Set<Class> interfaces = new HashSet<Class>(settings.getExtraInterfaces());
149        if(settings.isSerializable()) {
150            interfaces.add(Serializable.class);
151        }
152        if (settings.getSpiedInstance() != null) {
153            interfaces.add(MockitoSpy.class);
154        }
155        return interfaces;
156    }
157}
158
159
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

...Most popular Stackoverflow questions on InvocationListener

    No relevant questions found for this class 😞

Most used methods in InvocationListener

    No methods found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
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)