1 /* 2 * Copyright (c) 2017 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockitousage.junitrunner; 6 7 import org.junit.Test; 8 import org.junit.runner.JUnitCore; 9 import org.junit.runner.Result; 10 import org.junit.runner.RunWith; 11 import org.junit.runner.notification.Failure; 12 import org.mockito.junit.MockitoJUnitRunner; 13 import org.mockitousage.IMethods; 14 import org.mockitoutil.TestBase; 15 16 import static org.junit.Assert.assertEquals; 17 import static org.mockito.Mockito.mock; 18 import static org.mockito.Mockito.when; 19 20 public class UnusedStubsExceptionMessageTest extends TestBase { 21 22 //Moving the code around this class is tricky and may cause the test to fail 23 //We're asserting on full exception message which contains line numbers 24 //Let's leave it for now, updating the test is cheap and if it turns out hindrance we can make the assertion smarter. 25 @RunWith(MockitoJUnitRunner.class) 26 public static class HasUnnecessaryStubs { 27 IMethods mock1 = when(mock(IMethods.class).simpleMethod(1)).thenReturn("1").getMock(); 28 IMethods mock2 = when(mock(IMethods.class).simpleMethod(2)).thenReturn("2").getMock(); 29 IMethods mock3 = when(mock(IMethods.class).simpleMethod(3)).thenReturn("3").getMock(); 30 31 @Test usesStub()32 public void usesStub() { 33 assertEquals("1", mock1.simpleMethod(1)); 34 } 35 36 @Test usesStubWithDifferentArg()37 public void usesStubWithDifferentArg() { 38 assertEquals(null, mock2.simpleMethod(200)); 39 assertEquals(null, mock3.simpleMethod(300)); 40 } 41 } 42 43 @Test lists_all_unused_stubs_cleanly()44 public void lists_all_unused_stubs_cleanly() { 45 JUnitCore runner = new JUnitCore(); 46 //when 47 Result result = runner.run(HasUnnecessaryStubs.class); 48 //then 49 Failure failure = result.getFailures().get(0); 50 assertEquals("\n" + 51 "Unnecessary stubbings detected in test class: HasUnnecessaryStubs\n" + 52 "Clean & maintainable test code requires zero unnecessary code.\n" + 53 "Following stubbings are unnecessary (click to navigate to relevant line of code):\n" + 54 " 1. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.<init>(UnusedStubsExceptionMessageTest.java:0)\n" + 55 " 2. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.<init>(UnusedStubsExceptionMessageTest.java:0)\n" + 56 "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.", 57 filterLineNo(failure.getException().getMessage())); 58 } 59 } 60