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 static org.junit.Assert.assertEquals; 8 import static org.mockito.Mockito.mock; 9 import static org.mockito.Mockito.when; 10 11 import org.junit.Test; 12 import org.junit.runner.JUnitCore; 13 import org.junit.runner.Result; 14 import org.junit.runner.RunWith; 15 import org.junit.runner.notification.Failure; 16 import org.mockito.junit.MockitoJUnitRunner; 17 import org.mockitousage.IMethods; 18 import org.mockitoutil.TestBase; 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 25 // the assertion smarter. 26 @RunWith(MockitoJUnitRunner.class) 27 public static class HasUnnecessaryStubs { 28 IMethods mock1 = when(mock(IMethods.class).simpleMethod(1)).thenReturn("1").getMock(); 29 IMethods mock2 = when(mock(IMethods.class).simpleMethod(2)).thenReturn("2").getMock(); 30 IMethods mock3 = when(mock(IMethods.class).simpleMethod(3)).thenReturn("3").getMock(); 31 32 @Test usesStub()33 public void usesStub() { 34 assertEquals("1", mock1.simpleMethod(1)); 35 } 36 37 @Test usesStubWithDifferentArg()38 public void usesStubWithDifferentArg() { 39 assertEquals(null, mock2.simpleMethod(200)); 40 assertEquals(null, mock3.simpleMethod(300)); 41 } 42 } 43 44 @Test lists_all_unused_stubs_cleanly()45 public void lists_all_unused_stubs_cleanly() { 46 JUnitCore runner = new JUnitCore(); 47 // when 48 Result result = runner.run(HasUnnecessaryStubs.class); 49 // then 50 Failure failure = result.getFailures().get(0); 51 assertEquals( 52 "\n" 53 + "Unnecessary stubbings detected in test class: HasUnnecessaryStubs\n" 54 + "Clean & maintainable test code requires zero unnecessary code.\n" 55 + "Following stubbings are unnecessary (click to navigate to relevant line of code):\n" 56 + " 1. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.<init>(UnusedStubsExceptionMessageTest.java:0)\n" 57 + " 2. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.<init>(UnusedStubsExceptionMessageTest.java:0)\n" 58 + "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.", 59 filterLineNo(failure.getException().getMessage())); 60 } 61 } 62