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)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().)
{
throw new testException('test failed: reason is '
+ result.reason);
}
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: " +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.
result.reason);
No comments:
Post a Comment