0

I have below code

public class AccountHandler {

    public static void AccountValidation(list<account> acclist){
        set<string>AccName=new set<string>();
          set<string>dbnameset=new set<string>();
        for(account acc:acclist){
            AccName.add(acc.name);
        }
        for(account acc:[select name from account where name in :AccName])
        {
            dbnameset.add(acc.name);
        }
        for(account acc:acclist){
            if(dbnameset.contains(acc.Name)){
                acc.adderror('you cannot create account with Same name');
            }
        }
    }   
}

But if my existing record is like (BrahmanAccount) and i insert a record with name brahmanAccount then its not checking the duplicate.

Please suggest

test Class

@isTest
private class AccountHandler_Test{
  @testSetup
  static void setupTestData(){
    test.startTest();
    Account account_Obj = new Account(Name = 'Name395', Type = 'Prospect', Match_Billing_Address__c = false);
    Insert account_Obj; 
    test.stopTest();
  }
  static testMethod void test_AccountValidation_UseCase1(){
    List<Account> account_Obj  =  [SELECT Name,Type,Match_Billing_Address__c from Account];
    System.assertEquals(true,account_Obj.size()>0);
    AccountHandler obj01 = new AccountHandler();
    AccountHandler.AccountValidation(account_Obj);
  }
}
3

You could make both uppercase for the comparison:

for(account acc:[select name from account where name in :AccName])
{
    dbnameset.add(acc.name.toUpperCase());
}
for(account acc:acclist){
    if(dbnameset.contains(acc.Name.toUpperCase())){
        acc.adderror('you cannot create account with Same name');
    }
}

Btw. did you already consider using Duplicate Rules?

3
  • Thanks for suggesting Duplicate rules .I will go with that approach – sandy Oct 27 '17 at 7:13
  • but still can u please provide me test class changes.as i have written a test class but i dont thing its good – sandy Oct 27 '17 at 7:19
  • well all you need to do is insert two assignments with the same name and catch the exception. – Basti Oct 27 '17 at 7:55

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.