Activity Forums Salesforce® Discussions In which scenario we should use try catch in Test class in Salesforce?

  • In which scenario we should use try catch in Test class in Salesforce?

    Posted by Anjali on April 24, 2020 at 12:52 pm

    In which scenario we should use try catch in Test class in Salesforce?

    MOHIT replied 4 years, 8 months ago 2 Members · 1 Reply
  • 1 Reply
  • MOHIT

    Member
    April 24, 2020 at 1:20 pm

    when a test is deliberately provoking an exception and you want to check the exception, then a try/catch in the test is needed. A common case of this is where you are testing that a trigger is using addError to report an error back to a user:
    try {
    ...
    System.assert(false, 'Exception expected');
    } catch (DMLException e) {
    System.assert(e.getMessage().contains('expected message'), 'message=' + e.getMessage());
    }
    Note the test should fail if the exception isn't thrown, hence the System.assert(false, 'Exception expected');

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos