I an trying to create a testdatafactory which i can use to call in my tesclasses. What I want to achieve is small buildingblocks with which I call another method if a lookupfield needs to be filled. I tried this with account and opportunities which works great if I only call the opportunity from the test class but if I call both I get error: DUPLICATE_VALUE, duplicate value found: duplicates value on record with id: : []
Here is my example
@isTest
public class TestDataFactory {
public static List<Account> createAccounts(Integer numAccts) {
//List<Country__c> CountryList = createCountries(1);
Country__c c = new Country__c(Name = 'Nederland' , ISO2Code__c = 'NL' , IBANLength__c = 18, ISO3Code__c = 'NLD' , CountryNumber__c =151);
insert c;
List<Account> accList = new List<Account>();
for(Integer i=0;i<numAccts;i++) {
Account a = new Account(Name='TestAccount' +'-'+ i , Country__c = c.id);
accList.add(a);
}
insert accList;
return accList;
}
public static List<Opportunity> createOpportunities(Integer numOpp) {
List<Account> accList = createAccounts(numOpp);
List<Opportunity> oppList = new List<Opportunity>();
for(Integer i=0;i<numOpp;i++) {
Opportunity opp = new Opportunity(Name='TestOpportunity' +'-'+ i , Account = accList[0], StageName = 'Closed Won', CloseDate = system.today()+30);
oppList.add(opp);
}
insert oppList;
return oppList;
}
}
Works
@isTest
public class test {
@isTest static void tester(){
system.debug('createOpps ' + TestDataFactory.createOpportunities(5));
}
}
ERROR
@isTest
public class test {
@isTest static void tester(){
system.debug('createAccounts ' + TestDataFactory.createAccounts(5));
system.debug('createOpps ' + TestDataFactory.createOpportunities(5));
}
}
createOpportunities
method also callscreateAccount
, so it's called twice. Both of the times, the same Country gets created, I'm guessing there's a unique field on that object.