1

I can't test some rows in my code with duplicates, I try to make duplicate error in different ways but nothing helps. Could you assist?

Apex Class:

public class AccountExtensionController {

public Boolean hasDuplicateResult {get; set;}
public Boolean AccDuplicateFound {get; set;}
public Boolean ConDuplicateFound {get; set;}
public Boolean ContactCreated {get; set;}
public Boolean IsNewContact {get; set;}
public Boolean IsSuccess {get; set;}
public String AccountName {get; set;}
public String AccountId {get; set;}
public String FirstName {get; set;}
public String ContactId {get; set;}
public String LastName {get; set;}
public String AccPhone {get; set;}
public String Title {get; set;}
public String Email {get; set;}
public String Phone {get; set;}    
public Id UserId = UserInfo.getUserId();
public String HTMLContent='<h3 style="color:red;">Possible Duplicate Records are Found<br>You are creating a duplicate record. We recommend you use the existing record instead.</br></h3><p></p>';
private List<sObject> duplicateRecords;

Account a;
public class TaskSchedulerException extends Exception {}
ApexPages.StandardController controller;
public AccountExtensionController(ApexPages.StandardController con) {
    controller = con;
    a = (Account) con.getRecord();
    this.a = (a.Id == null) ? new Account() : [SELECT Id, Name, Phone FROM Account WHERE Id = :a.id];
    this.duplicateRecords = new List<sObject>();
    this.hasDuplicateResult = false;
    this.AccDuplicateFound = false;
    this.ConDuplicateFound = false;
    this.AccountId = '';
}

public Account getAccount() {
    return this.a;
}

public String getContent(){
            return HTMLContent;
    }

public List<sObject> getDuplicateRecords() {
    return this.duplicateRecords;
}    

public PageReference AccountSave(){
    try{
        List<String> errors =new List<String>();
        String allErrors ='';
        String PhoneRegEx = '^\\+([0-9 ]+)$';
        Pattern MyPattern = Pattern.compile(PhoneRegex);
        Matcher MyMatcher = MyPattern.matcher(accPhone);
        Boolean result = MyMatcher.matches();
        if(a.AccountSource == null){
            errors.add('Please select the Account Source for Account');
        }
        if(a.Type == null){
            errors.add('Please select the Type for Account');
        }
        if(result == false){
            errors.add('Please enter phone number in format +8 927 8376457 (only numbers and spaces with "+" are allowed)');
        }
        if (!errors.isEmpty()){                
            for (String val : errors) {
                allErrors = allErrors + val + '<br/>';
            }                
            throw new TaskSchedulerException(allErrors);
        } 

        Account acc = new Account();
        acc.Name = a.Name;
        acc.AccountSource = a.AccountSource;
        acc.Type = a.Type;
        acc.Phone = accPhone;
        acc.Website = a.Website;
        acc.Custom_Desk__c = a.Custom_Desk__c;
        acc.OwnerId = UserId;

        Database.DMLOptions dml = new Database.DMLOptions();
        dml.DuplicateRuleHeader.allowSave = false;
        dml.DuplicateRuleHeader.runAsCurrentUser = true;
        Database.SaveResult saveResult = DataBase.insert(acc, DML);

        if (!saveResult.isSuccess()) {
//*********From This line code doesn't covered
            for (Database.Error error : saveResult.getErrors()) {
                system.debug('Error='+saveResult.getErrors());
                if (error instanceof Database.DuplicateError) {                        
                    Database.DuplicateError duplicateError = (Database.DuplicateError)error;
                    Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();

                    //ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.Severity.ERROR, 'Duplicate Error: ' + duplicateResult.getErrorMessage());
                    //ApexPages.addMessage(errorMessage);

                    this.duplicateRecords = new List<sObject>();
                    Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();
                    Datacloud.MatchResult matchResult = matchResults[0];
                    Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();

                    for (Datacloud.MatchRecord matchRecord : matchRecords) {
                        System.debug('MatchRecord: ' + matchRecord.getRecord());
                        this.duplicateRecords.add(matchRecord.getRecord());
                    }
                    this.hasDuplicateResult = !this.duplicateRecords.isEmpty();
                    this.AccDuplicateFound = !this.duplicateRecords.isEmpty();
                }
            }
            return null;
        }
//********Till Here

        this.AccountId = acc.Id;
        AccountName = acc.Name;
        if(acc.Id != null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, '<a href=\'https://eu2.salesforce.com/'+acc.Id+'\' style="font-size: 15px;">Account '+acc.Name+' was successfully created.'));
            a.AccountSource = null;
            a.Type = null;
            a.Phone = null;
            a.Website = null;
            a.Custom_Desk__c = null;
        }            
    }
    catch (Exception exc) {
        ApexPages.addMessages(exc);             
    } 
    return null;
}  

public PageReference AccountSaveIgnore(){
    try{
        List<String> errors =new List<String>();
        String allErrors ='';
        hasDuplicateResult = false;
        String PhoneRegEx = '^\\+([0-9 ]+)$';
        Pattern MyPattern = Pattern.compile(PhoneRegex);
        Matcher MyMatcher = MyPattern.matcher(accPhone);
        Boolean result = MyMatcher.matches();
        if(a.AccountSource == null){
            errors.add('Please select the Account Source for Account');
        }
        if(a.Type == null){
            errors.add('Please select the Type for Account');
        }
        if(result == false){
            errors.add('Please enter phone number in format +8 927 8376457 (only numbers and spaces with "+" are allowed)');
        }
        if (!errors.isEmpty()){                
            for (String val : errors) {
                allErrors = allErrors + val + '<br/>';
            }                
            throw new TaskSchedulerException(allErrors);
        } 

        Account acc = new Account();
        acc.Name = a.Name;
        acc.AccountSource = a.AccountSource;
        acc.Type = a.Type;
        acc.Phone = accPhone;
        acc.Website = a.Website;
        acc.Custom_Desk__c = a.Custom_Desk__c;
        acc.OwnerId = UserId;

        Database.DMLOptions dml = new Database.DMLOptions();
        dml.DuplicateRuleHeader.allowSave = true;
        dml.DuplicateRuleHeader.runAsCurrentUser = true;
        Database.SaveResult saveResult = DataBase.insert(acc, DML);

        this.AccDuplicateFound = false;

        AccountId = acc.Id;
        AccountName = acc.Name;
        if(acc.Id != null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, '<a href=\'https://eu2.salesforce.com/'+acc.Id+'\' style="font-size: 15px;">Account '+acc.Name+' was successfully created.'));
            a.AccountSource = null;
            a.Type = null;
            a.Phone = null;
            a.Website = null;
            a.Custom_Desk__c = null;
        }            
    }
    catch (Exception exc) {
        ApexPages.addMessages(exc);             
    } 
    return null;
}

public PageReference ContactSave(){
    try{
        List<String> errors =new List<String>();
        String allErrors ='';
        String PhoneRegEx = '^\\+([0-9 ]+)$';
        Pattern MyPattern = Pattern.compile(PhoneRegex);
        Matcher MyMatcher = MyPattern.matcher(Phone);
        Boolean result = MyMatcher.matches();
        if(Title == null){
            errors.add('Please select the Title for Contact');
        }
        if(FirstName == null){
            errors.add('Please select the First Name for Contact');
        }
        if(LastName == null){
            errors.add('Please select the Last Name for Contact');
        }
        if(result == false){
            errors.add('Please enter phone number in format +8 927 8376457 (only numbers and spaces with "+" are allowed)');
        }
        if (!errors.isEmpty()){                
            for (String val : errors) {
                allErrors = allErrors + val + '<br/>';
            }                
            throw new TaskSchedulerException(allErrors);
            system.debug('Error='+AllErrors);
        }
        Contact con = new Contact();
        con.FirstName = FirstName;
        con.LastName = LastName;
        con.AccountId = AccountId;
        con.Phone = Phone;
        con.Title = Title;
        con.Email = Email;
        con.OwnerId = UserId;            

        Database.DMLOptions dml = new Database.DMLOptions();
        dml.DuplicateRuleHeader.allowSave = false;
        dml.DuplicateRuleHeader.runAsCurrentUser = true;
        Database.SaveResult saveResult = DataBase.insert(con, DML);

        if (!saveResult.isSuccess()) {
            for (Database.Error error : saveResult.getErrors()) {
                if (error instanceof Database.DuplicateError) {
                    Database.DuplicateError duplicateError = (Database.DuplicateError)error;
                    Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();

                    //ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.Severity.ERROR, 'Duplicate Error: ' + duplicateResult.getErrorMessage());
                    //ApexPages.addMessage(errorMessage);

                    this.duplicateRecords = new List<sObject>();
                    Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();
                    Datacloud.MatchResult matchResult = matchResults[0];
                    Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();

                    for (Datacloud.MatchRecord matchRecord : matchRecords) {
                        System.debug('MatchRecord: ' + matchRecord.getRecord());
                        this.duplicateRecords.add(matchRecord.getRecord());
                    }
                    this.hasDuplicateResult = !this.duplicateRecords.isEmpty();
                    this.ConDuplicateFound = !this.duplicateRecords.isEmpty();
                }
            }
            return null;
        }

        IsSuccess = saveResult.IsSuccess();
        ContactCreated = true;
        this.ContactId = con.id;

        if(con.Id != null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, '<a href=\'https://eu2.salesforce.com/'+con.Id+'\' style="font-size: 15px;">Contact '+con.LastName+' '+con.FirstName+' successfully created.'));
            FirstName = null;
            LastName = null;
            Phone = null;
            Title = null;
            Email = null;
        }
    }
    catch (Exception exc) {
        ApexPages.addMessages(exc);             
    } 
    return null;
}

public PageReference ContactSaveIgnore(){
    try{
        List<String> errors =new List<String>();
        String allErrors ='';
        hasDuplicateResult = false;
        String PhoneRegEx = '^\\+([0-9 ]+)$';
        Pattern MyPattern = Pattern.compile(PhoneRegex);
        Matcher MyMatcher = MyPattern.matcher(Phone);
        Boolean result = MyMatcher.matches();
        if(Title == null){
            errors.add('Please select the Title for Contact');
        }
        if(FirstName == null){
            errors.add('Please select the First Name for Contact');
        }
        if(LastName == null){
            errors.add('Please select the Last Name for Contact');
        }
        if(result == false){
            errors.add('Please enter phone number in format +8 927 8376457 (only numbers and spaces with "+" are allowed)');
        }
        if (!errors.isEmpty()){                
            for (String val : errors) {
                allErrors = allErrors + val + '<br/>';
            }                
            throw new TaskSchedulerException(allErrors);
            system.debug('Error='+AllErrors);
        }
        Contact con = new Contact();
        con.FirstName = FirstName;
        con.LastName = LastName;
        con.AccountId = AccountId;
        con.Phone = Phone;
        con.Title = Title;
        con.Email = Email;
        con.OwnerId = UserId;            

        Database.DMLOptions dml = new Database.DMLOptions();
        dml.DuplicateRuleHeader.allowSave = true;
        dml.DuplicateRuleHeader.runAsCurrentUser = true;
        Database.SaveResult saveResult = DataBase.insert(con, DML);

        this.ConDuplicateFound = false;

        ContactCreated = true;
        ContactId = con.id;

        if(con.Id != null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, '<a href=\'https://eu2.salesforce.com/'+con.Id+'\' style="font-size: 15px;">Contact '+con.LastName+' '+con.FirstName+' successfully created.'));
            FirstName = null;
            LastName = null;
            Phone = null;
            Title = null;
            Email = null;
        }
    }
    catch (Exception exc) {
        ApexPages.addMessages(exc);             
    } 
    return null;
}

public PageReference Next(){
    IsNewContact = true;
    return null;
}

public PageReference Back(){
    PageReference pageRef = new PageReference('https://c.eu2.visual.force.com/apex/AccountQuickCreate');
    return pageRef;
}

public PageReference NewCase(){
    PageReference pageRef = new PageReference('https://eu2.salesforce.com/setup/ui/recordtypeselect.jsp?ent=01Ib0000000WzBx&retURL=%2F'+AccountId+'&save_new_url=%2Fa0O%2Fe%3FCF00Nb0000007gPgK%3D'+AccountName+'%26CF00Nb0000007gPgK_lkid%3D'+AccountId+'%26retURL%3D%252F'+AccountId);
    return pageRef;
}

public PageReference NewCommunication(){
    system.debug('ContactId='+contactId);
    PageReference pageRef = new PageReference('https://c.eu2.visual.force.com/apex/TaskScheduler?AccountId='+AccountId+'&returnurl=https%3A%2F%2Feu2.salesforce.com%2F'+AccountId);
    return pageRef;
}

}

My Test Class:

@IsTest
public class TestAccountExtensionController {

static testmethod void Test_DupAccountCreate(){        

    PageReference pgRef = Page.AccountQuickCreate;
    Test.setCurrentPageReference(pgRef);

    Account acc = new Account();
        acc.Name = 'Test';
        acc.AccountSource = 'Call In';
        acc.Type = 'Bank';
        acc.Phone = '+89484665373';
        acc.Website = 'www.test.ru';
        acc.Custom_Desk__c = 'Algo Desk';

    ApexPages.StandardController sc = new ApexPages.StandardController(acc);
    AccountExtensionController AccExt = new AccountExtensionController(sc);

    AccExt.AccPhone = '+8 948 466 53 73';
    AccExt.getAccount();
    AccExt.getContent();
    AccExt.getDuplicateRecords();
    AccExt.AccountSaveIgnore();
    AccExt.a.AccountSource = '';
    AccExt.AccountSaveIgnore();
    AccExt.a.Type = '';
    AccExt.AccountSaveIgnore();
    AccExt.AccountId = acc.Id;
}

static testmethod void Test_AccountCreate(){        

    PageReference pgRef = Page.AccountQuickCreate;
    Test.setCurrentPageReference(pgRef);

    Account acc = new Account();
        acc.Name = 'Test';
        acc.AccountSource = 'Call In';
        acc.Type = 'Bank';
        acc.Phone = '+8 948 466 53 73';
        acc.Website = 'www.test.ru';
        acc.Custom_Desk__c = 'Algo Desk';
    insert acc;

    ApexPages.StandardController sc = new ApexPages.StandardController(acc);
    AccountExtensionController AccExt = new AccountExtensionController(sc);

    AccExt.AccPhone = '+8 948 466 53 73';
    AccExt.AccountSave();
    AccExt.a.AccountSource = '';
    AccExt.AccountSave();
    AccExt.a.Type = '';  
    AccExt.AccountSave();  

    Account acc2 = new Account();
        acc2.Name = 'Test';
        acc2.AccountSource = 'Call In';
        acc2.Type = 'Bank';
        acc2.Phone = '+8 948 466 53 73';
        acc2.Website = 'www.test.ru';
        acc2.Custom_Desk__c = 'Algo Desk';
    insert acc2;        
}         

static testmethod void Test_ContactCreate(){        

    PageReference pgRef = Page.AccountQuickCreate;
    Test.setCurrentPageReference(pgRef);                

    Account acc = new Account();
        acc.Name = 'Test';
        acc.AccountSource = 'Call In';
        acc.Type = 'Bank';
        acc.Phone = '+89484665373';
        acc.Website = 'www.test.ru';
        acc.Custom_Desk__c = 'Algo Desk'; 
    insert acc;

    ApexPages.StandardController sc = new ApexPages.StandardController(acc);
    AccountExtensionController AccExt = new AccountExtensionController(sc);

    AccExt.Phone = '+8 948 466 53 73';
    AccExt.a.Name = 'test123';
    AccExt.a.AccountSource = 'Call in';
    AccExt.a.Type = 'Bank';
    AccExt.AccountSave();

    AccExt.Next();

    AccExt.ContactSave();
    AccExt.Title = 'Test';
    AccExt.FirstName = 'Test';
    AccExt.LastName = 'Test'; 
    AccExt.ContactSave();
    AccExt.ContactSaveIgnore();

    AccExt.Back();
    AccExt.NewCase();
    AccExt.NewCommunication();             
}

static testmethod void Test_DupContactCreate(){        

    PageReference pgRef = Page.AccountQuickCreate;
    Test.setCurrentPageReference(pgRef);

    Account acc = new Account();
        acc.Name = 'Test';
        acc.AccountSource = 'Call In';
        acc.Type = 'Bank';
        acc.Phone = '+89484665373';
        acc.Website = 'www.test.ru';
        acc.Custom_Desk__c = 'Algo Desk';

    ApexPages.StandardController sc = new ApexPages.StandardController(acc);
    AccountExtensionController AccExt = new AccountExtensionController(sc);

    AccExt.Phone = '+8 948 466 53 73';
    AccExt.a.Name = 'test123';
    AccExt.a.AccountSource = 'Call in';
    AccExt.a.Type = 'Bank';
    AccExt.AccountSave();

    AccExt.Next();

    AccExt.ContactSaveIgnore();
    AccExt.Title = 'Test';
    AccExt.FirstName = 'Test';
    AccExt.LastName = 'Test'; 
    AccExt.ContactSaveIgnore();
}
}
  • Viktor - please see How to Ask to get the most from the Community. In particular, there is way too much code here; reduce the scope of the problem to its minimum – cropredy Dec 29 '16 at 16:35
2

I suggest you create a common Test Setup Method to create the database that you're going to query in your test method to find duplicate records. Once you do that, when you run you actual test method, you can attempt to create essentially the same test record and your method will find the duplicate record.

Your other option would be to use a CSV file as a static resource to load test data via Test.loadData(Account.sObjectType, 'myResource'); to import the database you need in order to run your query against when you create new records in your test.

  • Hi! Thanks for the assist! I liked the idea with Test Setup Method. When i adding a test setup with account insert i doesn't change anything. – Viktor Dec 30 '16 at 8:00
  • Did you insert a list of accounts, then during your test method, attempt to insert another account that met your criteria for a similar or duplicate account? From looking at your code, the account has to already be in your database for the it to work and detect the duplicate. – crmprogdev Dec 30 '16 at 13:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.