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.bugs; 6 7 import org.junit.Test; 8 import org.mockito.Mock; 9 import org.mockitousage.IMethods; 10 import org.mockitoutil.TestBase; 11 12 import static org.junit.Assert.fail; 13 import static org.mockito.Mockito.when; 14 15 /** 16 * These tests check that ThrowsException#answer throws an instance returned 17 * by Throwable#fillInStackTrace of the provided throwable. 18 * 19 * <p>A well-behaved Throwable implementation must always return a reference to this 20 * from #fillInStackTrace according to the method contract. 21 * However, Mockito throws the exception returned from #fillInStackTrace for backwards compatibility 22 * (or the provided exception if the method returns null). 23 * 24 * @see Throwable#fillInStackTrace() 25 * @see <a href="https://github.com/mockito/mockito/issues/866">#866</a> 26 */ 27 public class FillInStackTraceScenariosTest extends TestBase { 28 29 @Mock IMethods mock; 30 31 private class SomeException extends RuntimeException {} 32 33 class NullStackTraceException extends RuntimeException { 34 public Exception fillInStackTrace() { 35 return null; 36 } 37 } 38 39 class NewStackTraceException extends RuntimeException { 40 public Exception fillInStackTrace() { 41 return new SomeException(); 42 } 43 } 44 45 //issue 866 46 @Test 47 public void avoids_NPE() { 48 when(mock.simpleMethod()).thenThrow(new NullStackTraceException()); 49 try { 50 mock.simpleMethod(); 51 fail(); 52 } catch(NullStackTraceException e) {} 53 } 54 55 @Test 56 public void uses_return_value_from_fillInStackTrace() { 57 when(mock.simpleMethod()).thenThrow(new NewStackTraceException()); 58 try { 59 mock.simpleMethod(); 60 fail(); 61 } catch(SomeException e) {} 62 } 63 } 64