Page 1 of 1

Unit Testing for Exceptions

PostPosted: Tue Jul 03, 2012 6:35 pm
by jgarfield
In order for unit tests to really provide full coverage you need to make sure you are testing that your function throws exceptions when it's supposed to (lack of arguments, bad arguments, etc).

Currently we're rolled our own solution for this with the following function

Code: Select all
function assertException(fMethod, aArg, sMessage)
{
   var bCaught = false;
   try
   {
      fMethod.apply(null, aArg);
   }
   catch (e)
   {
      bCaught = true;
   }
   
   if (!bCaught)
   {
      jsunit.fail(sMessage);
   }
}


But would be nice if our jsunit natively provided this kind of functionality. In other unit testing packages I've seen things like assertFail or assertThrows.

Official Request: https://support.servoy.com/browse/SVY-2596

Re: Unit Testing for Exceptions

PostPosted: Thu Jul 05, 2012 11:23 pm
by omar
Hi,

Did you see the help for the JSUnit node in the Solution Explorer? Unless you mean something else what you ask for is already there?

Code: Select all
//Fails a test. AssertionFailedError is always thrown.
jsunit.fail("Fail test");

Re: Unit Testing for Exceptions

PostPosted: Fri Jul 06, 2012 3:08 pm
by jgarfield
Yes, I've checked that out...it's actually what I use to make my work-around method above :-)

jsunit.fail() is a way to force a unit test failure
what I'm looking for is a way to test for the successful throwing of an exception.
For instance:

Code: Select all
function add(a, b) {
   if (a == null | b == null) {
      throw "ArgumentException";
   }
   return a + b;
}

function test_add(){
   //Unit test should pass because "ArgumentException" was thrown
   jsunit.assertException(add(null, null));
}

Re: Unit Testing for Exceptions

PostPosted: Tue Jul 10, 2012 6:20 pm
by jcompagner
things like that is normally done like:

Code: Select all
function test_add() {

   try {
     add(1,2);
     jsunit.fail();
   } catch (e) {
    // should come in here
   }
}