Some time ago, I asked about this topic in the post Should be Triggers inactive by default in Unit Tests? However, my question wasn't precise enough.
I'd like to pose the question once again, this time being more precise:
Should triggers be inactive by default during the creation of test data?
Let's assume that I need to create test data and I'm unable to mock my tests. When creating test data in the @TestSetup
method, it shouldn't trigger the execution of trigger logic. This can sometimes pose problems due to long-running logic, which might affect deployment times and could even lead to SOQL/DML limit exceptions before the tests begin, especially in large projects with multiple teams.
Next disadvantage: Integration logic within triggers. I would like to test my controller that has a simple query, but I need to mock integration since triggers contain it.
Do you have any concerns regarding this approach?
Talk is cheap, show me the code:
@IsTest
private class MyControllerTest {
@TestSetup
static void setup() {
TriggerFramework.disableAllTriggers();
// create Account
// create Contact
// etc
TriggerFramework.enableAllTriggers();
}
@IsTest
static void getAccountsTest() {
// get test data
Test.startTest();
// my test
Test.stopTest();
// asserts
}
}
Perhaps the Test Data Creation framework could include a built-in function like TriggerFramework.disableAllTriggers();
, so that developers wouldn't need to explicitly invoke TriggerFramework.disableAllTriggers();
and TriggerFramework.enableAllTriggers();
every time in @TestSetup
.