Differences

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

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
student:junit:v5 [2020/01/15 15:55] bernstdhstudent:junit:v5 [2021/01/19 11:20] bernstdh
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 an advanced feature of Java (and many languagescalled [[https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html|"lambda expressions"]], so we will demonstrate a less commonly used, but simpler, 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()  +
-          throws IllegalArgumentException +
-  { +
-    assertThrows(IllegalArgumentException.class, () -> {new Atom("O", -8, -16);}); +
-  } +
-</code> +
- +
-This approach uses a //Lambda expression//, a representation of a class with a single-method.  +
-(Note that ''%%IllegalArgumentException%%'' is an unchecked   exception. Hence, this code will compile even if the test method does   not specify that it re-throws the exception. If you are testing for   a checked exception then the test method must specify that it re-throws   the exception.) +
- +
- +
-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 189: 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 ====