I need help in writing test class for following apex class. Could anyone please suggest how to create test data,test the following method defined in apex class with positive and negative scenarios and use of System.assertEquals() to make sure each scenario had the expected outcome.
customAppName field is multiselect picklist on customObject
public with Sharing class abcService{
@AuraEnabled
public static List<customObject> xyzMethod(){
UserAppInfo userAppInfo = [SELECT Id, AppDefinitionId FROM UserAppInfo WHERE UserId =
:UserInfo.getUserId() LIMIT 1];
AppDefinition appDefinition = [SELECT DurableId, Label FROM AppDefinition Where DurableId =
:userAppInfo.AppDefinitionId LIMIT 1];
String appName = appDefinition.Label;
System.debug('appName------->' + appName);
return [SELECT custom fields FROM customObject WHERE customAppName includes (:appName)];
}
}
When I started creating test data got fields not writeable issue for UserAppInfo and AppDefinition.
Based on the comments mentioned in the post, I started with test class but not able to cover the scenarios.
@isTest
public class abcServiceTest{
@testSetup
public static void testSetup(){
}
@isTest static void testPositiveScenario(){ //Passing App name
User u = someClass.testUserCreate();
System.runAs(u){
Test.startTest();
customObject__c customObjectObj = new customObject__c(custom_Id__c = 'Id_01', custom_Name__c = 'Test Name AA', customAppName__c = 'Test App AA');
insert customObjectObj;
List<customObject__c> customList = [SELECT custom_Id__c, custom_Name__c, customAppName__c FROM customObject__c WHERE customAppName__c INCLUDES ('Test App AA')];
System.debug('customList---------->' + customList);
System.assertEquals(1, customList.size());
Test.stopTest();
}
}
@isTest static void testNegativeScenario(){
User u = someClass.testUserCreate();
System.runAs(u){
Test.startTest();
customObject__c customObjectObj = new customObject__c(custom_Id__c = 'Id_02', custom_Name__c = 'Test Name BB', customAppName__c = 'Test App BB');
insert customObjectObj;
List<customObject__c> customList = [SELECT custom_Id__c, custom_Name__c, customAppName__c FROM customObject__c WHERE customAppName__c INCLUDES ('Test App CC')];
System.debug('customList---------->' + customList);
System.assertEquals(0, customList.size());
Test.stopTest();
}
}
}
Could anyone suggest how to have xyzMethod() covered. Any kind of help is appreciated.
canonical-qa
tag. Your question about how to control the test environment when working with metadata objects is more complex. If you search SFSE, you'll find a number of questions about mocking these objects using dependency injection and JSON deserialization. These are advanced techniques and may require more research and learning.