0

I've below method which I am trying to call from the Apex Test class, but when I call below method from Test class this query doesn't fetch any result. If I manully execute the query, then I get the result.

Why is this happening ?

public static string createBulkQuery(List<string> componentToShow){
        string UserLang = '';
        Id userId = UserInfo.getUserId();
        userContacts = new List<Contact>();  

        userContacts = [Select id,Preferred_Name__c,Correspondence_Language_Formula__c,FirstName,LastName,Position_Title__c,Correspondence_Language__c,Brand_Non_Brand__c,Manager_Flag__c,Work_Location_Country__c, Additional_Privileges__c,(Select Work_Location_Building_Name__c ,Global_Grade__c, Work_Location_Country__c ,Work_Location_City__c ,Work_Location_State__c,Location__c,Primary__c,Work_Location_Type__c,Job_Function__c,Job_Sub_Function__c,High_Level_Organization__c,Job_Area__c FROM Employee_Related_Information__r) FROM Contact WHERE RelatedUser__c=:userId Limit 1]; 

        if(userContacts.size() > 0){
            Contact currentUserContact = userContacts[0];

            //Checking User Language
            if(String.isNotBlank(currentUserContact.Correspondence_Language__c)){
                UserLang = '\''+currentUserContact.Correspondence_Language__c+'\'';
            }
        }
    }
}

I write below Test class, still making updates

@isTest 
static void testBulk(){
    Test.startTest();
    Profile p = [SELECT Id FROM Profile WHERE Name = :portalEmp];

    String orgId = UserInfo.getOrganizationId();
    String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
    Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
    String uniqueName = orgId + dateString + randomInt;

    User u = new User(  firstname = 'John',
                        lastName = 'Doe',
                        email = uniqueName + '@test' + orgId + '.org',
                        Username = uniqueName + '@test' + orgId + '.org',
                        EmailEncodingKey = 'ISO-8859-1',
                        Alias = uniqueName.substring(18, 23),
                        TimeZoneSidKey = 'America/Los_Angeles',
                        LocaleSidKey = 'en_US',
                        isActive = true,
                        LanguageLocaleKey = 'en_US',
                        ProfileId = p.Id);
    insert u;

    System.runAs(new User(Id = UserInfo.getUserId())){
        List<string> checkInComponents = new List<string>{'Request Catalog', 'Short Menu Catalog'};
        String queryValue = ProjectUtil.createBulkQuery(checkInComponents);
    }

    System.assert(u != null);

    Test.stopTest();
}

Even if I run this code normally using Anonymous window. I get the result. But through Apex test class I dont get any result.

Shanti
  • 161
  • 9

1 Answers1

2

Unit tests execute in an isolated environment. They cannot see the data in your database. This is a good thing: when tests depend on your data, they become fragile and easily fail if changes are made in the database.

Instead of relying on data in the organization, your test methods should always create synthetic data and insert it to be used in the test method. Data inserted during a test method is rolled back after the test completes, so there's no effect on your real database.

You can do this data creation either in each test method itself, or in an @testSetup annotated method in the test class. If you choose to use @testSetup, be aware that it is executed in a separate transaction and any references you hold to the data created there are invalidated and must be queried fresh.

How To Write Good Unit Tests is a great reference on unit testing practices. Additionally, you will probably want to read through Understanding Test Data from the Apex Developer Guide.

David Reed
  • 92,733
  • 13
  • 84
  • 157