You need to sign in to do that
Don't have an account?
Alexandra Petrescu
Help with a test class for Apex Trigger
Hi,
I am extremely new at writing apex code and I managed to write a trigger, but I don't quite know how to write a test class for it. My trigger looks like this:
trigger Changestage on Opportunity ( before update) {
set<ID> oppId = new set<ID>();
for (Opportunity opp: Trigger.new) {
if ((opp.StageName == 'Detailed Design') && (trigger.oldMap.get(opp.Id).StageName == 'Concept Design') && (opp.Equipment_Margin__c == null)) {
opp.addError('Cannot move the stage to Detailed Design if the Equipment Margin is empty');
}
}
}
Any help is much appreciated.
Thank you!
Alexandra
I am extremely new at writing apex code and I managed to write a trigger, but I don't quite know how to write a test class for it. My trigger looks like this:
trigger Changestage on Opportunity ( before update) {
set<ID> oppId = new set<ID>();
for (Opportunity opp: Trigger.new) {
if ((opp.StageName == 'Detailed Design') && (trigger.oldMap.get(opp.Id).StageName == 'Concept Design') && (opp.Equipment_Margin__c == null)) {
opp.addError('Cannot move the stage to Detailed Design if the Equipment Margin is empty');
}
}
}
Any help is much appreciated.
Thank you!
Alexandra
to create test claases we have to do-Creating Test Class
1-Data Creation. ...
2-@isTest annotation. ...
3-testMethod keyword. ...
4-Test.startTest() and Test.stopTest() ...
4-System.assert() ...
For more Help visit urls
https://www.tutorialspoint.com/apex/apex_testing.htm
Using This code you can also cover error code coverage ,this class is giving 100% coverage
All Answers
Please use below test class code:
Mark it as Best Answer, if it helps
Below is a code for the same . In order to pass the test class you need to add one line above the addError i.e ( if (!Test.isRunningTest()) ) this will not allow to execute the add error line, hence the test class will pass and the code coverage will be 75% (necessary for deployment) . In Case if you don’t write the above statement , in that case the test class will fail , thus it will give a error which will gave in add error line and the code Coverage of the trigger will be 100%.
Hope it helps you.
Apex Trigger Code : Test Class Code :
Screenshot :
Regards,
Akshay
to create test claases we have to do-Creating Test Class
1-Data Creation. ...
2-@isTest annotation. ...
3-testMethod keyword. ...
4-Test.startTest() and Test.stopTest() ...
4-System.assert() ...
For more Help visit urls
https://www.tutorialspoint.com/apex/apex_testing.htm
Using This code you can also cover error code coverage ,this class is giving 100% coverage
Regards,
Alexandra