You need to sign in to do that
Don't have an account?
Getting duplicate errors in Test class
I have written a trigger on the Campaign Member object that gives users access to our subscription service when their campagn status changes to 'Free Trial'. The trigger works without fail but the test is failing because of this error:
System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>: []
Here is my code:
@isTest public with sharing class Test_Trial_Campaign { static testMethod void test(){ list<Id> IdLst = new list<Id>(); list<CampaignMember> cMemL = new list<CampaignMember>(); Campaign testC = new Campaign(isActive = true, ActualCost = 0, Name = 'SystemTest'); insert testC; system.debug(testC); CampaignMemberStatus status = new CampaignMemberStatus(CampaignId = testC.Id, HasResponded = true, label = 'Free Trial', SortOrder = 2); insert new list<CampaignMemberStatus>{status}; for (Integer i=0; i<10; i++){ Lead testL = new Lead(FirstName = 'Test', LastName = 'Testerino'+i, email = 'test@testing.co'+i, Trial_Product__c = 'SUB-RTE-01'); insert testL; CampaignMember mem = new CampaignMember(CampaignId = testC.Id, LeadId = testL.Id, Status = 'Free Trial'); IdLst.add(testL.Id); insert mem; CampaignMember testerino = [SELECT Id, Status from CampaignMember where id =:mem.Id]; system.debug(testerino); } list<Lead> lList = [SELECT Id, isConverted From Lead Where Id IN: IdLst]; for (Lead l: lList){ system.debug(l); system.assert(l.IsConverted == true); } } }
It fails when attempting to insert the CampaignMemberStatus. I have tried multiple workarounds, all of which have failed. Any insight is greatly apprechiated.
Try changing the line from insert new list<CampaignMemberStatus>{status}; to insert status;
That was what I had before and I was getting the same error.
Thanks for your response.
This error comes when you try to insert a duplicate. For example: if you have some field marked as unique and when you try to insert another record with a value in the field which already exists in Salesforce DB.
CampaignMemberStatus insert is probably failing because you already have a record in salesforce with the same name. In such a case query and use the existing record rather than trying to create a new one with same name.
-Anand
Try using upsert instead of insert.
Thanks for your suggestions.
I have tried both of these already but to no avail.
There is no record in the database that shares this name.
Also upsert gives me the same error. Any additional help is greatly appreciated.
Have you checked the API version of the test class? Is it 24 or later ? Update to the curent version if not already and then test.
I had high hopes for this one since it was actually using version 23 but, I tried both version 25 and 26 and ran into the same error.