[SalesForce] Create Group and Group member for test method salesforce

How can I create Group with certain name and add group members to that group for Test classes?

As I am using 'ABC' developer name group in my class, So now I am writing test class to cover those lines.

But When I try to insert the test group in my test class, I am getting this error. [System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_DEVELOPER_NAME, This Developer Name already exists or has been previously used. Please choose a different name.: [DeveloperName] ]

Group testGroup = new Group();
        testGroup.Name = 'testGroup';
        testGroup.DeveloperName = 'ABC';
        INSERT testGroup;

Due to my understanding, DML in test classes are just creating during test. And I didn't set seeAllData=true in my test class too. So should be separated with real data?

Can someone share me their knowledge?

Best Answer

There's some funkiness around Chatter related objects and whether they're visible during tests. For instance, I've found in the past that if you're following your maximum number of records in Chatter and a run a test that tries to subscribe you to one more the test will blow up, even though you can't actually see or access the EntitySubscription objects. In that case the solution was to just insert a new user to run the tests as which is a best practice anyway.

Does your code depend on that particular developer name? If so I'd be inclined to use seeAllData=true since the functionality of your code depends on it existing.

You could just use a private string member variable in the class that accesses a group by name, which defaults to 'ABC' but could then be overridden during a test to match the name of a group inserted in the test method. To generate a unique name for the group before inserting drop a timestamp into the string and you should be set.