2

I am learning testing and came across the following: why is my test method not working as I expect and returning 0 records to me?

//test method

@isTest
static void searchContacts(){
    Contact testContact = new Contact(FirstName='First Name', LastName='Last Name', Email = '[email protected]', Contact_Level__c = 'Primary');
    upsert testContact;
    String searchKeyWord = 'Name';
    List<Contact> searchContact = ContactsManagerAuraController.searchContacts(searchKeyWord);
    System.assertEquals(1, searchContact.size());
}

//ContactsManagerAuraController

@AuraEnabled
public static List<Contact> searchContacts(String searchKeyword){
    return [FIND: searchKeyword IN ALL FIELDS RETURNING Contact(Name, Email, Contact_Level__c, Account.Name, Owner.Name, CreatedBy.Name, CreatedDate)][0];
}

//error

System.AssertException: Assertion Failed: Expected: 1, Actual: 0

1 Answer 1

9

Unit tests do not use the Search Index. This is because search indexes are not updated in real-time, so your search would fail anyways. Instead, you have to specify the results that should be returned:

Contact testContact = new Contact(FirstName='First Name', LastName='Last Name', Email = '[email protected]', Contact_Level__c = 'Primary');
upsert testContact;
String searchKeyWord = 'Name';
// Set the desired search results
Test.setFixedSearchResults(new Id[] { testContact.Id });
List<Contact> searchContact = ContactsManagerAuraController.searchContacts(searchKeyWord);
System.assertEquals(1, searchContact.size());

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .