/
MockitoExtension.java
64 lines (52 loc) · 2.22 KB
/
MockitoExtension.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.example.mockito;
import static org.mockito.Mockito.mock;
import java.lang.reflect.Parameter;
import org.junit.gen5.api.extension.ExtensionContext;
import org.junit.gen5.api.extension.ExtensionContext.Namespace;
import org.junit.gen5.api.extension.ExtensionContext.Store;
import org.junit.gen5.api.extension.InstancePostProcessor;
import org.junit.gen5.api.extension.MethodInvocationContext;
import org.junit.gen5.api.extension.MethodParameterResolver;
import org.junit.gen5.api.extension.ParameterResolutionException;
import org.junit.gen5.api.extension.TestExtensionContext;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* {@code MockitoExtension} showcases the {@link InstancePostProcessor}
* and {@link MethodParameterResolver} extension points of JUnit 5 by
* providing dependency injection support at the field level via Mockito's
* {@link Mock @Mock} annotation and at the method level via our demo
* {@link InjectMock @InjectMock} annotation.
*
* @since 5.0
*/
public class MockitoExtension implements InstancePostProcessor, MethodParameterResolver {
private static final Namespace namespace = Namespace.of(MockitoExtension.class);
@Override
public void postProcessTestInstance(TestExtensionContext context) {
MockitoAnnotations.initMocks(context.getTestInstance());
}
@Override
public boolean supports(Parameter parameter, MethodInvocationContext methodInvocationContext,
ExtensionContext extensionContext) {
return parameter.isAnnotationPresent(InjectMock.class);
}
@Override
public Object resolve(Parameter parameter, MethodInvocationContext methodInvocationContext,
ExtensionContext extensionContext) throws ParameterResolutionException {
Store mocks = extensionContext.getStore(namespace);
return getMock(parameter.getType(), mocks);
}
private Object getMock(Class<?> mockType, Store mocks) {
return mocks.getOrComputeIfAbsent(mockType, type -> mock(mockType));
}
}