forked from mockito/mockito
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DefaultMockitoSession.java
81 lines (69 loc) · 2.72 KB
/
DefaultMockitoSession.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* Copyright (c) 2018 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.framework;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.MockitoSession;
import org.mockito.exceptions.misusing.RedundantListenerException;
import org.mockito.internal.exceptions.Reporter;
import org.mockito.internal.junit.TestFinishedEvent;
import org.mockito.internal.junit.UniversalTestListener;
import org.mockito.plugins.MockitoLogger;
import org.mockito.quality.Strictness;
import java.util.List;
public class DefaultMockitoSession implements MockitoSession {
private final String name;
private final UniversalTestListener listener;
public DefaultMockitoSession(List<Object> testClassInstances, String name, Strictness strictness, MockitoLogger logger, boolean reportStubbingErrors) {
this.name = name;
listener = new UniversalTestListener(strictness, logger, reportStubbingErrors);
try {
//So that the listener can capture mock creation events
Mockito.framework().addListener(listener);
} catch (RedundantListenerException e) {
Reporter.unfinishedMockingSession();
}
try {
for (Object testClassInstance : testClassInstances) {
MockitoAnnotations.initMocks(testClassInstance);
}
} catch (RuntimeException e) {
//clean up in case 'initMocks' fails
listener.setListenerDirty();
throw e;
}
}
@Override
public void setStrictness(Strictness strictness) {
listener.setStrictness(strictness);
}
@Override
public void finishMocking() {
finishMocking(null);
}
@Override
public void finishMocking(final Throwable failure) {
//Cleaning up the state, we no longer need the listener hooked up
//The listener implements MockCreationListener and at this point
//we no longer need to listen on mock creation events. We are wrapping up the session
Mockito.framework().removeListener(listener);
//Emit test finished event so that validation such as strict stubbing can take place
listener.testFinished(new TestFinishedEvent() {
@Override
public Throwable getFailure() {
return failure;
}
@Override
public String getTestName() {
return name;
}
});
//Validate only when there is no test failure to avoid reporting multiple problems
if (failure == null) {
//Finally, validate user's misuse of Mockito framework.
Mockito.validateMockitoUsage();
}
}
}