Note that there are some explanatory texts on larger screens.

plurals
  1. POBad form for JUnit test to throw exception?
    primarykey
    data
    text
    <p>I'm pretty new to JUnit, and I don't really know what best practices are for exceptions and exception handling.</p> <p>For example, let's say I'm writing tests for an IPAddress class. It has a constructor IPAddress(String addr) that will throw an InvalidIPAddressException if addr is null. As far as I can tell from googling around, the test for the null parameter will look like this.</p> <pre><code>@Test public void testNullParameter() { try { IPAddress addr = new IPAddress(null); assertTrue(addr.getOctets() == null); } catch(InvalidIPAddressException e) { return; } fail("InvalidIPAddressException not thrown."); } </code></pre> <p>In this case, try/catch makes sense because I know the exception is coming.</p> <p>But now if I want to write testValidIPAddress(), there's a couple of ways to do it:</p> <p>Way #1:</p> <pre><code>@Test public void testValidIPAddress() throws InvalidIPAddressException { IPAddress addr = new IPAddress("127.0.0.1"); byte[] octets = addr.getOctets(); assertTrue(octets[0] == 127); assertTrue(octets[1] == 0); assertTrue(octets[2] == 0); assertTrue(octets[3] == 1); } </code></pre> <p>Way #2:</p> <pre><code>@Test public void testValidIPAddress() { try { IPAddress addr = new IPAddress("127.0.0.1"); byte[] octets = addr.getOctets(); assertTrue(octets[0] == 127); assertTrue(octets[1] == 0); assertTrue(octets[2] == 0); assertTrue(octets[3] == 1); } catch (InvalidIPAddressException e) { fail("InvalidIPAddressException: " + e.getMessage()); } } </code></pre> <p>Is is standard practice to throw unexpected exceptions to JUnit or just deal with them yourself?</p> <p>Thanks for the help.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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