Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If <code>A</code> is your system under test, it doesn't make any sense to mock it, and it rarely makes sense to spy on it. Your implementation in <code>testExpectedException2</code> is the right one; the boilerplate code is necessary because without a <code>try</code> block Java will not let any code run after the method is intercepted (as I described in <a href="https://stackoverflow.com/a/13224598/1426891">this previous SO answer</a>).</p> <p>Though Mockito won't be any help, JUnit will. The <code>@Test(expected=foo)</code> parameter actually has a more-flexible alternative, the built-in <a href="http://junit.org/javadoc/4.9/org/junit/rules/ExpectedException.html" rel="nofollow noreferrer"><code>ExpectedException</code> JUnit rule</a>:</p> <pre><code>public class CheckExceptionsWithMockitoTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testExpectedException1() { A a = new A(); thrown.expect(RuntimeException.class); thrown.expectMessage(containsString("cause1")); a.doSomethingThatThrows(); } } </code></pre> <p>Mockito <em>would</em> come in handy in a separate test checking whether your method wraps an arbitrary exception while preserving its message, which would look roughly like this:</p> <pre><code>@Test public void doSomethingShouldWrapExceptionWithPassedMessage() { Dependency dependency = Mockito.mock(Dependency.class); when(dependency.call()).thenThrow(new IllegalArgumentException("quux")); A a = new A(dependency); thrown.expect(RuntimeException.class); thrown.expectMessage(containsString("quux")); a.doSomethingThatThrows(); } </code></pre> <p>Be careful to avoid the temptation to make this a common pattern in your tests. If you are catching an exception thrown from your system under test, you're effectively ceding control back to the SUT's consumer. There should be little left to test in the method afterwards, except the properties of the exception and MAYBE the state of your system, both of which should be rare enough that try/catch boilerplate is forgivable.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload