[SalesForce] Unable to insert group during tests – “Group Already Exists” with SeeAllData=False

Create a class to automatically add user to chatter groups. I wrote a test class to cover the code. The class is working fine and covering code if I add SeeAllData=true.

Issue:
If I remove seeAllData=true, the test class is throwing an exception : List has no rows assignment to Sobject.

As I cannot deploy this to production. Is there any other way I can cover this code?

Class:

@future
public static void AddTochatter(Set<Id> uIds){

List<User> users=[select id,Name,Username from User id in :uIds];

List<String> groups=new List<String>{'ABC'};
List<CollaborationGroup> cGroups=[select id, Name from CollaborationGroup where name in :groups];

List<CollaborationGroupMember> cGMem=new List<CollaborationGroupMember>();

 for (User user : users)
     {

  for (CollaborationGroup chatterGroup : cGroups)// **the test code is not entering for loop**
      {

      CollaborationGroupMember c = 
       new CollaborationGroupMember(
                      CollaborationGroupId=chatterGroup.id,
                            MemberId = user.Id);
       cGMem.add(c);

      }   
    }
 if(cGMem.Size()>0){    
 insert cGMem;
 }

Test Class:

@isTest

    private class addChatter_test{
    static testMethod void Method1 (){


        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 

          User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
                EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
                LocaleSidKey='en_US', ProfileId = p.Id, 
                UserName='test123@test.com');
                System.runAs ( new User(Id = UserInfo.getUserId()) ) {
                    insert u;

                }
              // It is not retrieving anything and If I try to insert it is giving error group already exists 
            CollaborationGroup cgroups=[Select id,Name from CollaborationGroup where Name ='ABC']; 

    }}

It is not retrieving anything and If I try to insert it is giving error group already exists

Best Answer

I know this is an older post, but I wanted to provide the reasoning in case anyone else comes across this. Existing CollaborationGroups are not visible during a test unless SeeAllData=True, but they are still evaluated for the unique group name requirement.

You could set your 'groups' list to use a different set of groups when a test is running, then create those groups at the beginning of your test.

For example, use the following in your Class:

List<String> groups = !Test.isRunningTest() ? new List<String>{'ABC'} : new List<String>{'TestGroup'};

Then insert a CollaborationGroup named 'TestGroup' at the beginning of your Test Class:

CollaborationGroup g = new CollaborationGroup(Name='TestGroup', CollaborationType='Public');
insert g;