Activity Forums Salesforce® Discussions Why we use try and catch block in test classes in Salesforce ?

  • Achintya

    Member
    August 29, 2019 at 5:35 am

    You can use try-catch inside a test class, and this is how you can test a class which you have written and that will throw an exception.

    Like if your class includes something like this

    if (aSomeTestCondition == true) {
    } else {
    Exception e = new myClassException();
    e.setMessage('Incorrect aSomeTestCondition');
    throw e;
    }

    Then your test class would include code to cause this error, and would include a try catch like this

    try {
    Test.startTest();
    //Call your class in a way that causes the exception
    Test.stopTest();
    } catch (myClass.myClassException e) {
    System.assertEquals('Incorrect bSomeTestCondition', e.getMessage());
    }

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos