Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
student:junit:v5 [2020/02/23 10:50] – Fixed the description of assertThrows() bernstdhstudent:junit:v5 [2020/04/23 11:25] – [Testing Methods that Throw Exceptions] changing order, add sub-headings for convenient deep linking stewarmc
Line 147: Line 147:
  
  
-There are several ways to test for thrown exceptions in JUnit. The most common is to use the ''%%assertThrows()%%'' method. For examplesuppose   the constructor of the ''%%Atom()%%'' class is required to throw an   ''%%IllegalArgumentException%%'' when the numeric parameters   are negativeOne might test this is follows.+There are several ways to test for thrown exceptions in JUnit. The most common is to use the ''%%assertThrows()%%'' method, but this approach depends on a feature of Java (and many languages called [[https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html|"lambda expressions"]], so we will demonstrate a less commonly used approach first.
  
 +=== Testing for exceptions ===
  
-<code java> +One can invoke the methods that is supposed to throw an expression in a ''%%try-catch%%'' block, and use the ''%%fail()%%'' method. For example:
-  /** +
-   * Test that the constructor validates properly. +
-   */ +
-  @Test +
-  public void constructor_IllegalArguments() +
-  { +
-    assertThrows(IllegalArgumentException.class, () -> {new Atom("O", -8, -16);}); +
-  } +
-</code> +
- +
-This approach uses a //Lambda expression//, a representation of a class with a single-method.  +
- +
- +
-Alternatively, one can invoke the methods that is supposed to throw an expression in a ''%%try-catch%%'' block, and use the ''%%fail()%%'' method. For example:+
  
 <code java> <code java>
Line 187: Line 174:
 </code> </code>
  
 +=== Testing for exceptions canonically (with lambda expressions) ===
  
 +Suppose the constructor of the ''%%Atom()%%'' class is required to throw an   ''%%IllegalArgumentException%%'' when the numeric parameters   are negative. One might test this is follows.
  
 +
 +<code java>
 +  /**
 +   * Test that the constructor validates properly.
 +   */
 +  @Test
 +  public void constructor_IllegalArguments()
 +  {
 +    assertThrows(IllegalArgumentException.class, () -> {new Atom("O", -8, -16);});
 +  }
 +</code>
 +
 +This approach uses a //Lambda expression//, a representation of a class with a single-method. 
 ==== Other Useful Methods in the Assert Class ==== ==== Other Useful Methods in the Assert Class ====