001/* 002 * Copyright 2011 Atteo. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014package org.atteo.moonshine.tests; 015 016import org.junit.rules.MethodRule; 017import org.junit.runners.model.FrameworkMethod; 018import org.junit.runners.model.Statement; 019import org.mockito.Mockito; 020 021/** 022 * Resets the mocks registered using {@link MockAndBind}. 023 * <p> 024 * Usage: 025 * <pre> 026 * class Test { 027 * @ClassRule 028 * public static final MoonshineRule moonshine = new Moonshine(); 029 * 030 * @Rule 031 * public ResetMocksRule resetMocks = new ResetMocksRule(moonshine); 032 * } 033 * </pre> 034 */ 035public class ResetMocksRule implements MethodRule { 036 private final MoonshineRule moonshineRule; 037 038 public ResetMocksRule(MoonshineRule moonshineRule) { 039 this.moonshineRule = moonshineRule; 040 } 041 042 @Override 043 public Statement apply(final Statement base, FrameworkMethod method, final Object target) { 044 return new Statement() { 045 @Override 046 public void evaluate() throws Throwable { 047 resetMocks(); 048 base.evaluate(); 049 Mockito.validateMockitoUsage(); 050 } 051 }; 052 } 053 054 private void resetMocks() { 055 for (Object mock : moonshineRule.getMocks().values()) { 056 Mockito.reset(mock); 057 } 058 } 059 060}