function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kpetersonkpeterson 

Is it acceptable to raise errors in unit tests?

Is it acceptable to cause failures in a unit test when obtaining 100% coverage on code that raises an error on purpose?  Like in the case that I have an insert trigger check to make sure another record doesn't already exists and it raises an error on the object if it does so it doesn't get inserted.  This causes an error in the unit test because I intentionally cause the error to get 100% coverage.  Is this against a unit test best practice or how do you get around this?
sfdcfoxsfdcfox
If your code is supposed to cause an error, you must use try/catch blocks to catch the error and make sure that the error is the error you expected to receive. Take a look at the Force.com Cookbook examples on unit tests for additional information. You should call System.assert(false) to fail a test on purpose (e.g. if an error is NOT thrown) or System.assertEquals(error, "You can not do blah, blah, blah") type asserts; if the assert fails, then your test fails and you have a logic error. If you receive the right error, then your assertEquals will be true and your test will complete successfully.

Edit: Here's an example:
Code:
...
  try {
  package.doSomething();
  System.assert(false);
  } catch(error)
  { System.assertEquals(error, "You have a problem.");
  }
...

I'm not 100% certain of the try/catch block offhand, as I'm a bit tired, but that's the general idea of a unit test.



Message Edited by sfdcfox on 12-05-2007 11:35 AM
kpetersonkpeterson
Thanks for the reply, I understand what you are saying and it makes sense now.  I just need to assert whatever custom error message it throws.
TehNrdTehNrd
I throw errors in all my triggers when testing as I want to make sure they are all caught and enterd into a custom exception log I've created. So I can't see there being a issue with cause errors as you want to make sure the error handling is working correctly.