1 /* 2 * Copyright (c) 2018 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockito.internal.junit; 6 7 import org.junit.runners.model.FrameworkMethod; 8 import org.junit.runners.model.Statement; 9 import org.mockito.Mockito; 10 import org.mockito.MockitoSession; 11 import org.mockito.internal.session.MockitoSessionLoggerAdapter; 12 import org.mockito.internal.util.MockitoLogger; 13 import org.mockito.quality.Strictness; 14 import org.mockito.junit.MockitoRule; 15 16 /** 17 * Internal implementation. 18 */ 19 public class JUnitRule implements MockitoRule { 20 21 private final MockitoLogger logger; 22 private Strictness strictness; 23 private MockitoSession session; 24 25 /** 26 * @param strictness how strict mocking / stubbing is concerned 27 */ 28 public JUnitRule(MockitoLogger logger, Strictness strictness) { 29 this.logger = logger; 30 this.strictness = strictness; 31 } 32 33 @Override 34 public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { 35 return new Statement() { 36 public void evaluate() throws Throwable { 37 session = Mockito.mockitoSession() 38 .name(target.getClass().getSimpleName() + "." + method.getName()) 39 .strictness(strictness) 40 .logger(new MockitoSessionLoggerAdapter(logger)) 41 .initMocks(target) 42 .startMocking(); 43 Throwable testFailure = evaluateSafely(base); 44 session.finishMocking(testFailure); 45 if (testFailure != null) { 46 throw testFailure; 47 } 48 } 49 50 private Throwable evaluateSafely(Statement base) { 51 try { 52 base.evaluate(); 53 return null; 54 } catch (Throwable throwable) { 55 return throwable; 56 } 57 } 58 }; 59 } 60 61 public MockitoRule silent() { 62 return strictness(Strictness.LENIENT); 63 } 64 65 public MockitoRule strictness(Strictness strictness) { 66 this.strictness = strictness; 67 // session is null when this method is called during initialization of 68 // the @Rule field of the test class 69 if (session != null) { 70 session.setStrictness(strictness); 71 } 72 return this; 73 } 74 } 75