1package org.mockito.internal.framework; 2 3import org.mockito.Mockito; 4import org.mockito.MockitoAnnotations; 5import org.mockito.MockitoSession; 6import org.mockito.exceptions.misusing.RedundantListenerException; 7import org.mockito.internal.exceptions.Reporter; 8import org.mockito.internal.junit.TestFinishedEvent; 9import org.mockito.internal.junit.UniversalTestListener; 10import org.mockito.internal.util.MockitoLogger; 11import org.mockito.quality.Strictness; 12 13public class DefaultMockitoSession implements MockitoSession { 14 15 private final Object testClassInstance; 16 private final UniversalTestListener listener; 17 18 public DefaultMockitoSession(Object testClassInstance, Strictness strictness, MockitoLogger logger) { 19 this.testClassInstance = testClassInstance; 20 listener = new UniversalTestListener(strictness, logger); 21 try { 22 //So that the listener can capture mock creation events 23 Mockito.framework().addListener(listener); 24 } catch (RedundantListenerException e) { 25 Reporter.unfinishedMockingSession(); 26 } 27 MockitoAnnotations.initMocks(testClassInstance); 28 } 29 30 public void finishMocking() { 31 //Cleaning up the state, we no longer need the listener hooked up 32 //The listener implements MockCreationListener and at this point 33 //we no longer need to listen on mock creation events. We are wrapping up the session 34 Mockito.framework().removeListener(listener); 35 36 //Emit test finished event so that validation such as strict stubbing can take place 37 listener.testFinished(new TestFinishedEvent() { 38 public Throwable getFailure() { 39 return null; 40 } 41 public Object getTestClassInstance() { 42 return testClassInstance; 43 } 44 public String getTestMethodName() { 45 return null; 46 } 47 }); 48 49 //Finally, validate user's misuse of Mockito framework. 50 Mockito.validateMockitoUsage(); 51 } 52} 53