0

I am writing unit test classes for trigger. Can we use dml statements within Test.Starttest and test.stopTest? What is the best practise?

Test.StartTest();
insert exList;
Test.StopTest();

Can I use Delete dml statement within try..catch?

Test.StartTest();
try{
    Delete exList;
}
catch(Exception e){
    System.debug(e.getMessage());
}
Test.StopTest();
1

1 Answer 1

2

See this Using Limits, startTest, and stopTest.

A short version of this is that Test.startTest() gives you a new set of governor limits and Test.stopTest() runs any outstanding asynchronous work. So if necessary code a unit test like this:

@IsTest
static void myTestMethod() {

    // Initialise data

    Test.startTest();

    // Invoke the code you are testing

    Test.stopTest();

    // Assert the results
}

But for many tests the features of Test.startTest() and Test.stopTest() are not needed so they can and should be left out.

On your specific questions:

  • Yes you can do a DML insert as you illustrate (to e.g. make a trigger run)
  • Yes you can do a DML delete as you illustrate, but unless you are trying to invoke an error condition, best to not include try/catch in your test and instead just let the test fail and the test runner will report the exception if an exception is thrown.

On a broader point about testing triggers, some people may argue that extracting the trigger logic out into separate Apex classes and calling those classes directly is a good way to go. Personally, I always test triggers - whether they have inline code or code extracted out into classes - by performing DML in the unit tests as there are fine-grained details related to e.g. whether the trigger is before or after that need to be covered by the tests to assert a trigger's actual behaviour in the running software.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .