User Story
As a Salesforce user,
I want the system to automatically create a new account with a unique name when I create an account with a name that already exists,
So that there are no duplicate records with the same name in the system.
Acceptance Criteria:
-
If no account with the specified name exists:
- The system creates an account with the provided name.
- Example: Input name "Bank Of America" → Account created with name "Bank Of America".
-
If one or more accounts with the specified name or duplicates already exist:
- The system appends a suffix 'Duplicate [N]' where N is the next sequential number.
- Example: Existing accounts "Bank Of America" and "Bank Of America Duplicate 1" → New account created as "Bank Of America Duplicate 2".
-
The system ensures no errors occur during the creation process.
-
The system provides a debug log to confirm the creation of the account.
Codes
public class AccountUtility {
public static void createAccount(String name) {
String searchKey = '%' + name + '%';
List<Account> accList = [SELECT Id, Name FROM Account WHERE Name LIKE :searchKey];
Account acc = new Account();
if (accList.size() > 0) {
acc.Name = name + ' Duplicate ' + String.valueOf(accList.size());
} else {
acc.Name = name;
}
try {
insert acc;
System.debug('Account created with ID: ' + acc.Id + ', Name: ' + acc.Name);
} catch (DmlException e) {
System.debug('Failed to create Account: ' + e.getMessage());
}
}
}
Test Class
@isTest
public class AccountUtilityTest {
@isTest
public static Void TestA(){
AccountUtility.CreateAccount('Bank Of America');
Account acc= [Select Id, Name From Account Limit 1];
System.Assert('Bank Of America'== acc.Name);
}
@isTest
public static Void TestB(){
Account acc =new Account();
acc.Name = 'Bank Of America';
insert acc;
AccountUtility.CreateAccount('Bank Of America');
Account acc2= [Select Id, Name From Account Order By CreatedDate ASC Limit 1];
System.Assert('Bank Of America 1'== acc2.Name);
}
}