You need to sign in to do that
Don't have an account?
Salesforce Admin2
How to write a trigger test class to help get my code coverage up to 75%
trigger CaseCommentValidate on CaseComment (before delete, before update) {
Id profileId=userinfo.getProfileId();
String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
system.debug('ProfileName'+profileName);
if (Trigger.isDelete) {
for (CaseComment caseComment : Trigger.old) {
Case parentCase = [Select Id, Parks__c, Works__c, Returned_Date__c from Case where Id =:caseComment.parentId];
if((parentCase.Works__c== TRUE || parentCase.Parks__c == TRUE) && parentCase.Returned_Date__c == null && profileName != 'System Administrator') {
caseComment.addError('Comments cannot be deleted on cases being integrated with ...');
}
}
}
else {
for (CaseComment caseComment : Trigger.new) {
CaseComment oldCaseComment = Trigger.oldMap.get(caseComment.ID);
Case parentCase = [Select status , Id, Parks__c, Works__c, Returned_Date__c from Case where Id =:caseComment.parentId];
if((parentCase.Works__c== TRUE || parentCase.Parks__c == TRUE) && parentCase.Returned_Date__c == null && profileName != 'System Administrator') {
if(caseComment.CommentBody != oldCaseComment.CommentBody)
caseComment.addError('Comments cannot be changed on cases being integrated with ...');
}
}
}
}
I need a test class for the above trigger but not sure how to write it to help get my code cover upto 75%. Right now my code coverage is at 67% when trying to deploy to production.
Id profileId=userinfo.getProfileId();
String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
system.debug('ProfileName'+profileName);
if (Trigger.isDelete) {
for (CaseComment caseComment : Trigger.old) {
Case parentCase = [Select Id, Parks__c, Works__c, Returned_Date__c from Case where Id =:caseComment.parentId];
if((parentCase.Works__c== TRUE || parentCase.Parks__c == TRUE) && parentCase.Returned_Date__c == null && profileName != 'System Administrator') {
caseComment.addError('Comments cannot be deleted on cases being integrated with ...');
}
}
}
else {
for (CaseComment caseComment : Trigger.new) {
CaseComment oldCaseComment = Trigger.oldMap.get(caseComment.ID);
Case parentCase = [Select status , Id, Parks__c, Works__c, Returned_Date__c from Case where Id =:caseComment.parentId];
if((parentCase.Works__c== TRUE || parentCase.Parks__c == TRUE) && parentCase.Returned_Date__c == null && profileName != 'System Administrator') {
if(caseComment.CommentBody != oldCaseComment.CommentBody)
caseComment.addError('Comments cannot be changed on cases being integrated with ...');
}
}
}
}
I need a test class for the above trigger but not sure how to write it to help get my code cover upto 75%. Right now my code coverage is at 67% when trying to deploy to production.
@isTest
public class TestCaseAssignment {
static testmethod void insertNewcase() {
List<Case> cases = new List<Case>();
for(integer i = 0 ; i< 20 ; i++)
{
Case joe = new Case();
joe.Service_Request_Type__c = 'Miscellaneous';
joe.Status = 'New';
joe.Origin = 'Phone';
joe.Priority = 'Medium';
joe.Location_Format__c='Street Address';
joe.Street_Name__c='LINCOLN ST';
joe.Street_Number__c='230';
cases.add(joe);
}
Database.insert(cases);
}
}
Moreover, I would suggest that you create a case such that it satisfy the conditions when the Case Comment is updated or deleted.
1. Update the Case Comment
2. Delete the Case Comment
This should trigger the two IF and ELSE statements sequentially and help you increase the Code Coverage.
Thanks
AR
@istest public with sharing class CaseTriggerTestfl{
public static testmethod void testCaseTrigger()
{
//When a new case (First Case) is created
case cs = new case();
cs.Subject= 'Testing';
cs.Origin='Phone';
cs.Description = 'FL Testing Triggers calls';
cs.Status ='Open';
cs.Location_Format__c='Street Address';
cs.Street_Name__c='LINCOLN ST';
cs.Street_Number__c='230';
cs.Send_Case_Creation_Email_to_Contact__c=False;
insert cs;
casecomment ccom = new casecomment ();
ccom.commentBody = cs.Description;
ccom.parentid = cs.id;
insert ccom;
cs.Send_Case_Creation_Email_to_Contact__c=True; //the updating of the send case creation email to contact checkbox should trigger the HandleLucityFieldUpdate trigger
update cs;
delete ccom; //the deleting the comments should trigger the LucityCaseCommentValidate trigger
delete cs; // deleting the case should trigger the LucityCaseValidation trigger
}
}
I used your Trigger and Test Class codes, created the custom fields and ran the Tests. You know what - I was able to achieve 100% code coverage :) I hope it gives the same results to you too.
Remember that you run the Test class with a profile other than System Administrator.
Here is the modified Test Class. Just copy and perform a Test run.
There are no changes done to the Trigger code.
Thanks
AR
If you found the reply useful that solved your problem then please mark it as best answer.
I guess the lines of code that I commented is causing this issue. Can you share the list of fields that are mandatory on the Case Object in your test environment.
Meanwhile, try the following Test Class and see if it runs successfully. I have uncommented the lines I commented earlier.
Let me know the results. Also share the error, if any after this new test run, with the details.
Thanks
AR
, the error I am getting is System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LucityCaseInsertion: execution of AfterInsert
caused by: line 15, column 61: trigger body is invalid and failed recompilation: Dependent class is invalid and needs recompilation:
insertcaseinlucity: class failed previous initial parse attempt: []
Not sure why the error is stating my trigger is invalid and failed recompilation because no changes has been made to the trigger since I have bee testing, I will try to recompile the trigger and see what happens. Any suggestions you have I would appreciate it. Than You
The error seems to be in your other Tigger 'LucityCaseInsertion'.
Therefore I strongly recommend you to do the following step by step -
1. First to test the current Tigger 'CaseCommentValidate', you can comment out the erroring Trigger 'LucityCaseInsertion'. I am pretty sure that after commenting the erroring Trigger, the other Trigger in discussion will work properly giving decent code coverage.
2. Once we are successful in the first step, then you can share the code for Trigger 'LucityCaseInsertion' along with any Test Class that you have written for it. We can look into getting it right.
Let me know how to think about this approach.
Thanks
AR
I finally figured my issue in the CaseTestTrigger Class. I added a field name named Lucity_WR_ID in the case script because I was trying to get a higher code coverage in the CaseCommentValidate Trigger. Come to find out I was going after the Lucity_WR_ID field incorrectly in the CaseTestTrigger class script, which caused my test class to error. I have fixed the CaseTestTrigger Class but I am still only get ting 76% code coverage. The issue now is I have not been able to write the appropriate script to CaseTestTrigger to test two area in the CaseCommentValidate Trigger.
The two problem areas that casetesttrigger are not touching are documented below. I am getting closer thanks to you Anupam. Still working on test class. I will let you know if I am able to increase my code coverage to at least 80% LOL!. Have an Awesome Day!
trigger CaseCommentValidate on CaseComment (before delete, before update) {
Id profileId=userinfo.getProfileId();
String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
system.debug('ProfileName'+profileName);
if (Trigger.isDelete) {
for (CaseComment caseComment : Trigger.old) {
Case parentCase = [Select Id, Lucity_Parks__c, Lucity_Public_Works__c, Lucity_Returned_Date__c from Case where Id =:caseComment.parentId];
if((parentCase.Lucity_Public_Works__c== TRUE || parentCase.Lucity_Parks__c == TRUE) && parentCase.Lucity_Returned_Date__c == null && profileName != 'System Administrator') {
caseComment.addError('Comments cannot be deleted on cases being integrated with Lucity'); -Problem Area 1
}
}
}
else {
for (CaseComment caseComment : Trigger.new) {
CaseComment oldCaseComment = Trigger.oldMap.get(caseComment.ID);
Case parentCase = [Select status , Id, Lucity_Parks__c, Lucity_Public_Works__c, Lucity_Returned_Date__c from Case where Id =:caseComment.parentId];
if((parentCase.Lucity_Public_Works__c== TRUE || parentCase.Lucity_Parks__c == TRUE) && parentCase.Lucity_Returned_Date__c == null && profileName != 'System Administrator') {
if(caseComment.CommentBody != oldCaseComment.CommentBody)
caseComment.addError('Comments cannot be changed on cases being integrated with Lucity'); --Problem Area 2
}
}
}
}
.@isTest
public class CaseTestTriggersFrances {
static testmethod void t1() {
//When a new case (First Case) is created
case cs = new case();
cs.Subject= 'Testing';
cs.Origin='Phone';
cs.Description = 'FL Testing Triggers calls';
cs.Status ='Open';
cs.Lucity_Public_Works_valid__c='yes';
cs.Location_Format__c='Street Address';
cs.Street_Name__c='LINCOLN ST';
cs.Street_Number__c='230';
cs.Send_Case_Creation_Email_to_Contact__c=False;
cs.Lucity_Returned_Date__c=null;
insert cs;
casecomment ccom = new casecomment ();
ccom.commentBody = cs.Description;
ccom.parentid = cs.id;
insert ccom;
try {
ccom.CommentBody = 'Changed the Description 1';
update ccom;
Delete ccom;
}
catch (Exception e) {
Boolean exceptionThrown = e.getMessage().contains('Comments cannot be changed on cases being integrated with ...')? true : false;
System.assertEquals(exceptionThrown, true);
}
// try {
// delete ccom;
// }
// catch (Exception e) {
// Boolean exceptionThrown = e.getMessage().contains('Comments cannot be deleted on cases being integrated with ...')? true : false;
// System.assertEquals(exceptionThrown, true);
// }
case cs2 = new case();
cs2.Subject= 'Testing';
cs2.Origin='Phone';
cs2.Description = 'FL Testing Triggers calls';
cs2.Status ='New';
cs2.Lucity_Public_Works_valid__c='yes';
cs2.Location_Format__c='Street Address';
cs2.Street_Name__c='LINCOLN ST';
cs2.Street_Number__c='230';
cs2.Send_Case_Creation_Email_to_Contact__c=False;
cs2.Lucity_Returned_Date__c=null;
insert cs2;
casecomment ccom2 = new casecomment ();
ccom2.commentBody = cs2.Description;
ccom2.parentid = cs2.id;
insert ccom2;
try{
ccom2.CommentBody = 'new test2';
update ccom2;
delete ccom2;
}
catch(Exception ex) {
System.assert(ex.getMessage().contains('Comments cannot be deleted on cases being integrated with Lucity'),
ex.getMessage() );
}
finally {
InsertCaseCommentInLucity iCom = new InsertCaseCommentInLucity();
// iCom.callCommentFuture(c.Lucity_WR_ID__c ,c.Id,true,cm.CommentBody);
// iCom.callCommentFuture(c.Lucity_WR_ID__c ,c.Id,false,null);
}
}
//t2 method test the LucityValidate trigger
static testmethod void t2() {
Case c = new Case(
Subject='testCase',
Service_Request_Type__c = 'SW New Container Request',
Description = 'FL Testing Triggers calls',
Recycling_Container_QTY__c=4,
Refuse_Container_QTY__c=4,
Customer_Type__c='Business',New_Container_Issue__c='First Container',
Payment_Most_Likely_Needed__c=TRUE,
Payment_Method__c='Pay in Person',
status='New',
Street_Number__c='230',
Street_Name__c='Lincoln st',
Lucity_Public_Works_valid__c='yes'
);
insert c;
Case cas = new Case(
Subject='testCase',
Service_Request_Type__c = 'Alarms: City Offices',
Lucity_User1_Type_Main__c ='Alarms: City Offices',
Lucity_Public_Works_Valid__c='yes',
status='New',Street_Number__c='230',
Street_Name__c='Lincoln st',
Description='Change Comments Test');
insert cas;
cas.parentId=c.id;
cas.Lucity_WR_ID__c = '99999';
cas.Lucity_Returned_Date__c=null;
update cas;
cas.status=null;
cas.Lucity_WR_ID__c = null;
Try{
update cas;
}
Catch(Exception ex){
//Assert Error Message
System.assert(ex.getMessage().contains('New cases being integrated with Lucity must have a Status = New'),
ex.getMessage() );
}
Try{
delete cas;
}
Catch(Exception ex){
//Assert Error Message
System.assert(ex.getMessage().contains('Cases being integrated with Lucity cannot be deleted'),
ex.getMessage() );
}
}
}
Is it that you are not logged in as System Administrator when you are running the Test Class? If yes then you need to use runAsmethod so that the code is executed using a System Administrator profile to achieve 100% code coverage.
Add the following bold lines within the t1 method as shown later.
So your entire test class should look like -
Thanks
AR
If you found the reply useful that solved your problem then please mark it as best answer.
the issue is that I am a system administrator that is testing the script but my issue is in order to test the if statement that states not equal to 'System Administrator'.
In other words I need to test script for a non-System Administrator user. So I did try to use your code in the following way but it gave me a " System.QueryException: List has no rows for assignment to SObject". p.S I modified it some what to incorporate one of our license's users. Thanks Anupam for all you assistance in help.
profileName != 'System Administrator'
@isTest
public class CaseTestTriggersFrances {
static testmethod void t1() {
Profile profileName = [SELECT Id,Name FROM Profile WHERE Name='Supervisors'];
User u = new User(Alias = 'mhicks', Email='mhicks@hampton.gov', EmailEncodingKey='UTF-8', LastName='Hicks',
LanguageLocaleKey='en_US',LocaleSidKey='en_US', ProfileId = profileName.Id, TimeZoneSidKey='America/New_York', UserName='mhicks@hampton.gov.staging');
System.runAs(u)
// system.debug('ProfileName'+profileName)
}
}
What it the line of code which is throwing this error?
Meanwhile, guessing it myself, I think you either mentioned a profile name ('Supervisors') wrongly as it does not exists or it is misspelt.
Check the screen shot of the same class that I have which is giving 100% code coverage. I would recommend you to use the standard user profile instead for a test run, making sure the spelling is correct.
Thanks
AR
If you find the reply useful which solves your problem then please mark it as best answer.
Anyways, share the code for all of them - Triggers and Test Classes. And for doing so use the <> button on the palette above, as it presents the code in readable format.
Thanks
AR