0

Can someone tell me how I can avoid using (seealldata=TRUE) BUT still be able to access an existing Chatter Group in a test class?

Example with use of the SeeAllData=TRUE clause;

//Find Chatter Group ID
CollaborationGroup BCIGroup = [Select Id,Name 
                               FROM CollaborationGroup 
                               WHERE Name = 'All Company'
                               LIMIT 1];

I am trying to add users to the group in my class but I run into a problem when creating the group, when seealldata is FALSE, because the test class still sees the chatter group to some degree. The group exists in both my sandbox and production environment.

Let me know if you want to see any of my code. This is part of a big chunk of code and there are a few classes involved so don't want to blast the forum with all the code.

1

It can be fairly simple to test these kind of data dependencies by shifting the source of the dependency slightly. For example, you could configure the Name you filter on so you can modify it in your test. Something like:

@TestVisible static String allCompanyGroupName = 'All Company';
public static CollaborationGroup bciGroup
{
    get
    {
        if (bciGroup == null)
            bciGroup = [
                SELECT Name FROM CollaborationGroup
                WHERE Name = :allCompanyGroupName
                LIMIT 1
            ]
        return BCIGroup;
    }
    private set;
}

Then in your test, you can just create your own group and change the name to match.

static final String GROUP_NAME = 'My_Test_Group_12345';
static testMethod void testBciGroup()
{
    CollaborationGroup testGroup = new CollaborationGroup(Name=GROUP_NAME);
    MyClass.allCompanyGroupName = GROUP_NAME;

    Test.startTest();
        CollaborationGroup queryResult = MyClass.bciGroup;
    Test.stopTest();

    system.assertEquals(testGroup.Id, queryResult.Id,
        'The correct record should be queried');
}

Note that because of the lazy loading pattern, you can pull this variable as many times as you want and it will consume just one query.

static final String GROUP_NAME = 'My_Test_Group_12345';
static testMethod void testBciGroup()
{
    CollaborationGroup testGroup = new CollaborationGroup(Name=GROUP_NAME);
    MyClass.allCompanyGroupName = GROUP_NAME;

    Test.startTest();
        CollaborationGroup queryResult;
        for (Integer i = 0; i < Limits.getLimitQueries() + 1; i++)
            queryResult = MyClass.bciGroup;
        Integer queriesConsumed = Limits.getQueries();
    Test.stopTest();

    system.assertEquals(testGroup.Id, queryResult.Id,
        'The correct record should be queried');
    system.assertEquals(1, queriesConsumed,
        'Only one query should be consumed');
}

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.