Tuesday, November 8, 2011

SalesForce Test Classes

I'm no expert on SalesForce, but I've been working with it for a year now, and I think I'm starting to get why things work the way they do.  One thing I figured out today was that it would sometimes be much more helpful if my test classes could fail with a descriptive message of what went wrong instead of failing on a generic assert.  The test classes I inherited from our consultants who wrote this do things like:
System.assert(result.isSuccess==true);
This is great on the surface, and we want to test this, but when the result fails, we really want to know why it failed.  To facilitate this, I came up with a new class, testException, that I can throw when I want a test to fail:
public class testException extends Exception {}
I can then make my tests fail with better information by using this exception.  For example, the System.assert example above, could be rewritten as:
if ( !result.isSuccess)
{
    throw new testException('test failed: reason is '
                            + result.reason);
}
Now, when the test fails, it will be obvious from the error why it failed, and I can include information about what led up to the failure.  (One note is that for some reason do you have to declare your own exception class.  You cannot throw new Exception().)

Admittedly, this isn't rocket science, but I thought it made a much better style for coding your tests.

UPDATE:
Did I mention that I'm still learning all this SalesForce stuff?  If it wasn't obvious, this'll help make it readily apparent. 

So I figured something out after writing this article and playing with the tests some more.  The System.assert() method actually has an additional form that allows you to do much the same thing:
System.assert(result.isSuccess==true, "operation failed: " +
                                       result.reason);
So I'm not sure if there's really any reason to define your own exception class just for unit tests.  It might be useful if you wanted to catch the exception in some case, but my test classes aren't doing that.

No comments:

Post a Comment

Search This Blog