function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
fiona gentryfiona gentry 

How to write tests that creates sample Case Type Data records, then runs the search and checks if what was returned matches expectations

Dear gurus.

How to write tests that creates sample Case Type Data records, then runs the search and checks if what was returned matches expectations

here is the apex class
 
public class Stack {
				@AuraEnabled(cacheable=true)
				public static List<LookupSearchResult> search(String searchTerm, List<String> selectedIds){
					if(String.isBlank(searchTerm) || searchTerm.length() < 2){
						return null;
					}
					String t = '%' + searchTerm + '%'; // decide how you want to search, "starts with", "includes" or what
					
					List<Case_Type_Data__c> records = [SELECT Id, Name, Level_1__c, Level_2__c, Level_3__c
						FROM Case_Type_Data__c
						WHERE Level_1__c LIKE :t OR Level_2__c LIKE :t OR Level_3__c LIKE :t
						ORDER BY Level_1__c, Level_2__c, Level_3__c
						LIMIT 20];
					
					/* You could also experiment with SOSL?
					records =  [FIND :('*' + searchTerm + '*') IN ALL FIELDS 
						RETURNING Case_Type_Data__c(Id, Name, Level_1__c, Level_2__c, Level_3__c)][0];
					*/
					
					List<LookupSearchResult> results = new List<LookupSearchResult>();
					for(Case_Type_Data__c ctd : records){
						results.add(new LookupSearchResult(ctd.Id, 'Case_Type_Data__c', 'standard:case_wrap_up', ctd.Name,
							String.join(new List<String>{ctd.Level_1__c , ctd.Level_2__c, ctd.Level_3__c}, '; ')
						));
					}
					return results;
				} 

			}

Regards,
Fiona​​​​​​​
Arun Kumar 1141Arun Kumar 1141

Hi, Fiona gentry,

For your above apex class below is the test class code you can take a look at that for your reference:

myTestDataFactory is used for creating records of Case_Type_Data__c object

@IsTest
private class StackTest {
	@testsetup
	private static void myTestDataFactory(){
		Case_Type_Data__c record1 = new Case_Type_Data__c(Name = 'Test Record 1', Level_1__c = 'Level 1', Level_2__c = 'Level 2', Level_3__c = 'Level 3');
        Case_Type_Data__c record2 = new Case_Type_Data__c(Name = 'Test Record 2', Level_1__c = 'Level 1', Level_2__c = 'Level 2', Level_3__c = 'Level 3');
        insert new List<Case_Type_Data__c>{record1, record2};
	}
    @IsTest
    static void testSearch() {
        test.startTest();
        List<Stack.LookupSearchResult> results = Stack.search('Test', new List<String>());
        test.stopTest();
		
        // Assert the results
        System.assertEquals(2, results.size());
        Stack.LookupSearchResult result1 = results[0];
        System.assertEquals(ctd1.Id, result1.recordId);
        System.assertEquals('Case_Type_Data__c', result1.sObjectType);
     
    }
}
 

If you find this answer helpful to you then mark this as the best answer.

Thanks