Show/Hide Toolbars

Unit Test Framework Manual

Navigation: Writing Test Cases

Checking Exceptions

Scroll Prev Top Next More

When performing some tests, you need to confirm that an operation throws an exception rather than continues normally.  This check can be done using a try-catch statement and the fail function.  This is an example:

 

  /**

   * Test 007 - Test of primary insured validation

   */

   public function test007PrimaryInsured() : void {

     try {

       var primary = searchRequest.PrimaryInsured

       fail("null primary insured not caught")

     } catch (e : IntegrationException) {

       assertEquals("ERR-2000001: Value cannot be null or empty: primary insured", e.Message)

     }

     return

   }

 

In this example, the developer is checking that access to the PrimaryInsured property will throw an IntegrationException if it has not been properly initialized.  The access is included in a Gosu try-catch statement.  The statement after access is a call to the fail function.  If the access to PrimaryInsured does not produce an exception, the fail function is called, throwing an AssertionException. If the test succeeds, the IntegrationException is caught, and the message is compared to the expected message using the assertEquals function.

 

Be careful that you do not catch an exception that is a parent class of AssertException.  For example, the following test method will incorrectly report success:

 

   public function test007PrimaryInsured() : void {

     try {

       var primary = searchRequest.PrimaryInsured

       fail("null primary insured not caught")

     } catch (e : Exception) {

       return

     }

     return

   }

 

In the above case, the fail may throw an AssertionException which the catch statement will catch. A correct alternative is:

 

   public function test007PrimaryInsured() : void {

     try {

       var primary = searchRequest.PrimaryInsured

     } catch (e : Exception) {

       return

     }

     fail("null primary insured not caught")

     return

   }