1 /* 2 * Copyright (c) 2016 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockito.exceptions.misusing; 6 7 import org.mockito.Mockito; 8 import org.mockito.MockitoSession; 9 import org.mockito.exceptions.base.MockitoException; 10 11 /** 12 * This exception indicates presence of unused stubbings. 13 * It is highly recommended to remove unused stubbings to keep the codebase clean. 14 * In a rare scenario that unused stubbing is a false negative you can opt out from the validation via 15 * (in order of ascending scope): 16 * <ol> 17 * <li>Declaring specific stubbing as 'lenient' - {@link Mockito#lenient()}</li> 18 * <li>Declaring specific mock as 'lenient' - {@link org.mockito.MockSettings#lenient()}</li> 19 * <li>Declaring all mocks in given test class or test method mock as 'lenient' with 20 * our JUnit support ({@link org.mockito.junit.MockitoJUnit}) or Mockito session ({@link MockitoSession})</li> 21 * </ol> 22 * 23 * <p> 24 * Unnecessary stubbings are stubbed method calls that were never realized during test execution. Example: 25 * <pre class="code"><code class="java"> 26 * //code under test: 27 * ... 28 * String result = translator.translate("one") 29 * ... 30 * 31 * //test: 32 * ... 33 * when(translator.translate("one")).thenReturn("jeden"); // <- stubbing realized during code execution 34 * when(translator.translate("two")).thenReturn("dwa"); // <- stubbing never realized 35 * ... 36 * </pre> 37 * Notice that one of the stubbed methods were never realized in the code under test, during test execution. 38 * The stray stubbing might be an oversight of the developer, the artifact of copy-paste 39 * or the effect not understanding the test/code. 40 * Either way, the developer ends up with unnecessary test code. 41 * In order to keep the codebase clean & maintainable it is necessary to remove unnecessary code. 42 * Otherwise tests are harder to read and reason about. 43 * <p> 44 * Mockito JUnit Runner triggers <code>UnnecessaryStubbingException</code> only when none of the test methods use the stubbings. 45 * This means that it is ok to put default stubbing in a 'setup' method or in test class constructor. 46 * That default stubbing needs to be used at least once by one of the test methods. 47 */ 48 public class UnnecessaryStubbingException extends MockitoException { UnnecessaryStubbingException(String message)49 public UnnecessaryStubbingException(String message) { 50 super(message); 51 } 52 } 53