Skip to main content

#Test Classes0 discutindo

I'm facing a problem while attempting to retrieve the networkId in my test class for a functionality that involves fetching a user's photo in a community context. In my method, I'm using Network.getNetworkId() to obtain the networkId, and then utilizing it to fetch the user's photo via ConnectApi.UserProfiles.getPhoto(networkId, userId). However, during the test class execution, the networkId is returning as null.

Despite referencing a StackExchange post for insights and ensuring the necessary permissions, the networkId is still coming up as null in the test class.

Could someone can provide insights on why the networkId might be returning null in the test class despite functioning correctly within the method? I'd greatly appreciate any suggestions or guidance on resolving this issue. Thank you!

 

#Apex  #Community  #Community Cloud  #Test Classes

1 resposta
  1. Mohit Kumar Agarwal (Dell Technologies) Forum Ambassador
    13 de mai. de 2024, 02:16
0/9000

global with sharing class ScheduledBatchable implements Schedulable{

global void execute(SchedulableContext sc) {

CronTrigger cronTrigger= [SELECT CronJobDetail.Name, PreviousFireTime, State FROM CronTrigger where State = 'EXECUTING' AND CronJobDetail.Name like 'Email%'];

List<Payroll__c> payroll = [SELECT Id, FORMAT(Row_DateTime_API01__c),Row_Text_API05__c,Row_Text_API06__c,RecordType.name,

FROM Payroll__c WHERE Row_DateTime_API01__c =: cronTrigger.PreviousFireTime];

PayrollSendEmailBatch payrollSendEmailBatch = new PayrollSendEmailBatch(payroll);

Database.executeBatch(payrollSendEmailBatch,200);

}

}

#Test Classes

1 resposta
0/9000

Hi All, 

 

I've been struggling with achieving the 75%+ coverage required for a trigger to prevent users from deleting files linked to Account. 

 

The trigger works as intended; allowing System Administrators OR users with a "File_Deletion" permission set to delete files 

 

Any advice is much appreciated!

 

Trigger

trigger PreventFileDeletion on ContentDocument (before delete) {    Boolean isAdmin = false;    Boolean hasPermissionSet = false;    // Check if running user has the SysAdmin profile    Profile adminProfile = [SELECT Id, Name FROM Profile WHERE Name = 'System Administrator' LIMIT 1];    if (UserInfo.getProfileId() == adminProfile.Id) {        isAdmin = true;    }    // Check if running user has "File Deletion" permission set if user is not SysAdmin    if(isAdmin == false){        PermissionSet ps = [SELECT Id, Name FROM PermissionSet WHERE Name = 'File_Deletion' LIMIT 1];        // Get current user's Id        Id userId = UserInfo.getUserId();         // Check for PermSet allowing deletion        PermissionSetAssignment psa = [SELECT id FROM PermissionSetAssignment WHERE AssigneeId = :userId AND PermissionSetId = :ps.id LIMIT 1];        if (psa != null) {            hasPermissionSet = true;        }    }    // If running user not SysAdmin and does not have "File Deletion" permission set run the logic    if (!isAdmin && !hasPermissionSet) {        // Check if any related ContentDocumentLink records exist with related AccountIds        Set<Id> accountIds = new Set<Id>();        // Gather ContentDocumentIds being deleted        for (ContentDocument cd : Trigger.old) {            accountIds.add(cd.Id);        }        // Query related ContentDocumentLink records        List<ContentDocumentLink> relatedLinks = [SELECT Id, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN :accountIds];        // Check if any related ContentDocumentLink records exist with AccountIds        for (ContentDocumentLink link : relatedLinks) {            if (link.LinkedEntityId.getSObjectType() == Account.SObjectType) {                // Prevent deletion and throw an error message                Trigger.oldMap.get(link.ContentDocumentId).addError('Files related to Accounts cannot be deleted.');            }        }    }}

Test Class (36% coverage)

@isTestprivate class TestPreventFileDeletion {    private static PermissionSet ps;    private static User SystemAdminUser;    private static User StandardUser;    private static User PermSetUser;    @TestSetup    static void setup() {        // Create test Acc        Account testAccount = new Account(name = 'Acme');        insert testAccount;        // Create test ContentDocument        ContentVersion cv = new ContentVersion();        cv.Title = 'Test Document';        cv.PathOnClient = 'test_document.txt';        cv.VersionData = Blob.valueOf('Test Content');        insert cv;        // Create a ContentDocumentLink between Acc & ContentDocument        ContentDocumentLink testLink = new ContentDocumentLink();        testLink.ContentDocumentId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id].ContentDocumentId;        testLink.LinkedEntityId = testAccount.Id;        testLink.ShareType = 'V';        insert testLink;    }    @isTest    static void AllowSystemAdminUser() {        // Retrieve profile for test        Profile adminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];        // Create SysAdmin user        SystemAdminUser = new User(            Alias = 'SysAdUsr',            Email = 'SystemAdminUser@test.com',            EmailEncodingKey = 'UTF-8',            LastName = 'Testing',            LanguageLocaleKey = 'en_US',            LocaleSidKey = 'en_US',            ProfileId = adminProfile.Id,            TimeZoneSidKey = 'America/Los_Angeles',            UserName = 'SystemAdminUser@test.com.hdyfjtutkg'        );        insert SystemAdminUser;        // Get Acc        Account testAccount = [SELECT id FROM Account LIMIT 1];        // Query ContentDocumentLink records related to the test Account        List<Id> relatedContentDocumentIds = new List<Id>();        for (ContentDocumentLink link : [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :testAccount.Id]) {            relatedContentDocumentIds.add(link.ContentDocumentId);        }        Test.startTest();        System.RunAs(SystemAdminUser){        // Attempt to delete the test ContentDocument as SystemAdmin            try {                delete [SELECT Id FROM ContentDocument WHERE Id IN :relatedContentDocumentIds];                //System.assert(false, 'Expected error not thrown');            } catch (DmlException e) {                //System.assert(e.getDmlMessage(0).contains('Files related to Accounts cannot be deleted.'), 'Unexpected error message');                System.debug('e.getDmlMessage(0) = ' + e.getDmlMessage(0));            }        }        Test.stopTest();    }    @isTest    static void PreventStandardUser() {        // Get Id the Standard User Profile        Profile StandardProfile = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];        // Create Standard Profile user        StandardUser = new User(            Alias = 'StandUsr',            Email = 'StandardUser@test.com',            EmailEncodingKey = 'UTF-8',            LastName = 'Testing',            LanguageLocaleKey = 'en_US',            LocaleSidKey = 'en_US',            ProfileId = StandardProfile.Id,            TimeZoneSidKey = 'America/Los_Angeles',            UserName = 'StandardUser@test.com.hdyfjtutkg'        );        insert StandardUser;        // Get Acc         Account testAccount = [SELECT id FROM Account LIMIT 1];        // Query ContentDocumentLink records related to the test Account        List<Id> relatedContentDocumentIds = new List<Id>();        for (ContentDocumentLink link : [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :testAccount.Id]) {            relatedContentDocumentIds.add(link.ContentDocumentId);        }        Test.startTest();        // Attempt to delete the test ContentDocument as Standard User        System.runAs(StandardUser){            try {                delete [SELECT Id FROM ContentDocument WHERE Id IN :relatedContentDocumentIds];                //System.assert(false, 'Expected error not thrown');            } catch (DmlException e) {                System.assert(e.getDmlMessage(0).contains('insufficient access rights on object id'), 'Unexpected error message');            }            }        Test.stopTest();    }    @isTest    static void AllowPermSetUser() {        // Get Id for Standard User Profile        Profile StandardUser = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];        // Retrieve Account for testing        Account testAccount = [SELECT id FROM Account LIMIT 1];        // Create a Standard Profile test user with PermSet        PermSetUser = new User(            Alias = 'PermSUsr',            Email = 'PermSetUser@test.com',            EmailEncodingKey = 'UTF-8',            LastName = 'Testing',            LanguageLocaleKey = 'en_US',            LocaleSidKey = 'en_US',            ProfileId = StandardUser.Id,            TimeZoneSidKey = 'America/Los_Angeles',            UserName = 'PermSetUser@test.com.hdyfjtutkg'        );        insert PermSetUser;        // Get the 'File_Deletion' permission set        ps = [SELECT id FROM PermissionSet WHERE Name='File_Deletion'];        // Assign Permission Set to the Standard User        PermissionSetAssignment psa = new PermissionSetAssignment(AssigneeId=PermSetUser.Id, PermissionSetId=ps.Id);        insert psa;        // Query ContentDocumentLink records related to the test Account        List<Id> relatedContentDocumentIds = new List<Id>();        for (ContentDocumentLink link : [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :testAccount.Id]) {            relatedContentDocumentIds.add(link.ContentDocumentId);        }        Test.startTest();        System.RunAs(PermSetUser){        // Attempt to delete the test ContentDocument as Standard User            try {                delete [SELECT Id FROM ContentDocument WHERE Id IN :relatedContentDocumentIds];                //System.assert(false, 'Expected error not thrown');            } catch (DmlException e) {                //System.assert(e.getDmlMessage(0).contains('Files related to Accounts cannot be deleted.'), 'Unexpected error message');            }        }        Test.stopTest();    }}

 

Trigger to Prevent File Deletion - Test Class Coverage Question

#Apex #Test Classes #Salesforce Developer #Salesforce Developers #Apex Class #Triggers #Developer Forums

2 respostas
  1. 20 de mar. de 2024, 12:57

    Sometimes in your if statements - like on line #11 - I'll do an "|| test.isRunningTest()" - and that way the loop will run during test - to get more test coverage.

    It's probably not the "correct" way to do it, but I works.

0/9000

Below is my code... I am bit confused how to write test class for this?

 

trigger TestAttachmentcontentDoc on ContentDocumentLink (before insert) 

{  

Schema.DescribeSObjectResult inv = Supporting_Documentation__c.sObjectType.getDescribe(); 

String prefix = inv.getKeyPrefix();

Map<Id, Id> doclinkedId = new Map<Id, Id>();     

String keyPrefix;     

for(ContentDocumentLink contentdoc : Trigger.New)      

{              

       keyPrefix = String.valueOf(contentdoc.LinkedEntityId).left(3);          

       if(prefix==keyPrefix)        

       {             

               doclinkedId.put(contentdoc.ContentDocumentId, contentdoc.LinkedEntityId);           

               System.debug('**doclinkedId***'+doclinkedId);

        }     

}     

Supporting_Documentation__c SD=new Supporting_Documentation__c();     

String keyvalue;     

if(doclinkedId.size()>0)    

{      

       SD=[Select Status__c from Supporting_Documentation__c where ID IN : doclinkedId.values()];

        keyvalue =String.valueOf(SD.Id).left(3); 

}     

integer i;         

for(ContentDocumentLink tgr : Trigger.New)     

{

       if( keyvalue ==prefix && SD.Status__c=='Closed')                    

       {                        

                  tgr.addError('Cannot modify attachment from an Closed Inquiry');                     

        }                         

 }  

}

 

#Content Document Link

#Test Classes

#Apex Trigger

2 respostas
  1. 24 de ago. de 2022, 11:01

    @isTest

    public class TestAttachmentcontentDoc{

    @isTest

    static void TestAttachment{

    Test.startTest();

    Supporting_Documentation__c SD=new Supporting_Documentation__c();     

    SD.status = 'Closed'; 

    Database.insert(SD);

    Test.stop Test();

    }

    }

0/9000

When deploying or removing a trigger, how does Rollup Helper determine which test classes to run? I was attempting to remove one of the triggers from our Production environment and two seemingly unrelated tests (Tests written for objects not involved in the Rollups in question) failed. We are aware of several outdated test classes in our org, so it's no surprise that they failed, but we are trying to figure out how or why Rollup Helper chose to utilize those specific tests.

 

Thank you for your help :)

2 comentários
  1. 18 de jul. de 2019, 20:56

    Hi Jacob,

    Thank you! I assumed it was running all tests, but I wasn't sure. I appreciate you clarifying for me

0/9000

I have created a test class that bulk inserts the records in vf page in queues.But my records are not inserting .It gives me errors

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateAccountAndContact: execution of BeforeInsert  caused by: System.NullPointerException: Attempt to de-reference a null object  Trigger.UpdateAccountAndContact: line 67, column 1: []

 

Above same error in my three methods-testAutoSetCallbackDate, testManuallySettingCallbackDate , testOpportunityFinder

 

System.NullPointerException: Attempt to de-reference a null object

 

and i have inserted system.debug statements to verify till where code reaches and i find out it is not inserting the records i bulk .

 

debugs.png

Means it is not displaying my 3rd debug 

 insert new Opportunity[]{              op1,op2, op3, op4, op5, op6, op7, op8, op9, op10, op12,op11     };         system.debug('opportunity insertion ends '); 

 

here is my complete test class

@IsTest

public with sharing class TestOpportunityFinderv2 {

@testSetup static void setupData(){

List<Trigger_Handler__c> lstTriggerhandler= new List<Trigger_Handler__c>();

lstTriggerhandler.add(new Trigger_Handler__c(Name='AfterTrigger',isActive__c = false));

lstTriggerhandler.add(new Trigger_Handler__c(Name='BeforeTrigger',isActive__c = true));

lstTriggerhandler.add(new Trigger_Handler__c(Name='CallBatch',isActive__c = true));

lstTriggerhandler.add(new Trigger_Handler__c(Name='DuplicateOppMerge',isActive__c = false));

insert lstTriggerhandler;

system.debug('after triggers');

Opportunity op1 = new Opportunity( Name='Op1', CloseDate = Date.newInstance(2016, 08, 3), Stage_Count__c = 0, StageName = 'New' ,Lead_Status__c='Following',Call_Back_Date__c = Date.newInstance(2016, 08, 2), Call_back_time__c = Time.newInstance( 3, 3, 3, 0 ) , In_Queue__c = false);

Opportunity op2 = new Opportunity( Name='Op2', CloseDate = Date.today(), Call_back_Date__c = Date.today(), Stage_Count__c = 5, StageName = 'New' ,Lead_Status__c='Following');

Opportunity op3 = new Opportunity( Name='Op3', CloseDate = Date.today(), Call_back_Date__c = Date.today(), Stage_Count__c = 1, StageName = 'New',Lead_Status__c='Following' );

Opportunity op4 = new Opportunity( Name='Op4', CloseDate = Date.today(), Call_back_Date__c = Date.today() - 3, Stage_Count__c = 1, StageName = 'New',Lead_Status__c='Following' );

Opportunity op5 = new Opportunity( Name='Op5', CloseDate = Date.today(), Last_Call__c = Date.today() - 5, Opportunity_Score__c = 100, Stage_Count__c = 7, StageName = 'New',Lead_Status__c='Following' );

Opportunity op6 = new Opportunity( Name='Op6', CloseDate = Date.today(), Call_back_Date__c = Date.today() - 3, Stage_Count__c = 5, StageName = 'New',Lead_Status__c='Following' );

Opportunity op7 = new Opportunity( Name='Op7', CloseDate = Date.today(), Call_back_Date__c = Date.today() - 2, Stage_Count__c = 5, StageName = 'New',Lead_Status__c='Following' );

Opportunity op8 = new Opportunity( Name='Op8', CloseDate = Date.today(), Last_Call__c = Date.today() - 10, Stage_Count__c = 4, StageName = 'New',Lead_Status__c='Following' );

Opportunity op9 = new Opportunity( Name='Op9', CloseDate = Date.today(), Last_Call__c = Date.today() - 8, Stage_Count__c = 6, StageName = 'New',Lead_Status__c='Following' );

Opportunity op10 = new Opportunity( Name='Op10', CloseDate = Date.today(), Last_Call__c = Date.today() - 7, Stage_Count__c = 8, StageName = 'New',Lead_Status__c='Following');

Opportunity op12 = new Opportunity( Name='Op10', CloseDate = Date.today(), Last_Call__c = Date.today() - 7, Stage_Count__c = 8, StageName = 'New',Lead_Status__c='Following',Call_back_time__c=System.now().time(),Call_back_date__c=system.today() -2 );

Opportunity op11 = new Opportunity( Name='Op11', CloseDate = Date.today(), Last_Call__c = Date.today() - 7, In_Queue__c = true, StageName = 'Following >>> Send to Queue',Lead_Status__c='Following' );

system.debug('opportunity insertion begins ');//debug statement displayed

insert new Opportunity[]{

op1,op2, op3, op4, op5, op6, op7, op8, op9, op10, op12,op11

};

system.debug('opportunity insertion ends '); //not displayed

}

private static Opportunity fetchNextOpportunity()

{

system.debug(' insidefetchNextopp');

Id op_id = OpportunityFinderV2.findNextOpportunity();

if( op_id == null ) return null;

system.debug('id '+op_id );

return [SELECT Name FROM Opportunity WHERE Id = :op_id];

}

private static Opportunity closeAndFetch( Opportunity op )

{

op.StageName = 'No - Can Get it Cheaper';

update op;

system.debug('inside fetch nect opp');

return fetchNextOpportunity();

}

@IsTest

public static void testOpportunityFinder()

{

Test.startTest();

Opportunity op = new Opportunity();

op = fetchNextOpportunity();

//System.assertEquals( 'Op1', op.Name );

//op = fetchNextOpportunity();

//System.assertEquals( 'Op1', op.Name );

/*for( Integer x = 2; x < 10; x++ ){

op = closeAndFetch( op );

System.debug('Fetched: ' + op.Name );

// System.assertEquals( 'Op' + x, op.Name );

}*/

Test.stopTest();

}

@IsTest

public static void testAutoSetCallbackDate(){

OpportunityFinderV2 objfin = new OpportunityFinderV2();

objfin.fake();

// Opportunity op1 = new Opportunity( Name='Op1', CloseDate = Date.today(), Stage_Count__c = 0, StageName = 'New' );

Opportunity op1 = new Opportunity( Name='Op1', CloseDate = Date.newInstance(2016, 08, 3), Stage_Count__c = 0, StageName = 'New' ,Lead_Status__c='Following',Call_Back_Date__c = Date.newInstance(2016, 08, 2), Call_back_time__c =Time.newInstance( 3, 3, 3, 0 ) , In_Queue__c = false);

insert op1;

Test.startTest();

OpportunityCallViewExtensionV2 ext = new OpportunityCallViewExtensionV2( new ApexPages.StandardController( op1 ));

ext.LogAndNext();

ext.fake();

System.assertEquals(

OpportunityCallViewExtensionV2.AddWorkDays( Date.today(), 3),

[SELECT Call_back_Date__c FROM Opportunity WHERE Id = :op1.Id].Call_back_date__c

);

Test.stopTest();

}

@IsTest

private static void testManuallySettingCallbackDate(){

Opportunity op1 = new Opportunity( Name='Op1', CloseDate = Date.today(), Stage_Count__c = 0, StageName = 'New' );

insert op1;

Test.startTest();

OpportunityCallViewExtensionV2 ext = new OpportunityCallViewExtensionV2( new ApexPages.StandardController( op1 ));

ext.NextCallbackProxy.Call_back_date__c = Date.newInstance( 1991, 03, 04 );

ext.NextCallbackProxy.Call_back_time__c = time.newInstance(1, 1, 1, 1);

ext.LogAndNext();

System.assertEquals(

Date.newInstance( 1991, 03, 04 ),

[SELECT Call_back_Date__c FROM Opportunity WHERE Id = :op1.Id].Call_back_date__c

);

Test.stopTest();

}

}

I think that is why it is giving null point exception as records not inserted.

Can anyone help how to insert record in bulk.

 

I think that is why it is giving null point exception as records not inserted.

Can anyone help how to insert record in bulk.

  

#Apex  #Test Classes  #Apex Test Classes  #VF  #Exception  #Sales Cloud

 

#Apex  #Test Classes  #Apex Test Classes  #VF  #Exception  #Sales Cloud

 

#Apex  #Test Classes  #Apex Test Classes  #VF  #Exception  #Sales Cloud

9 respostas
  1. 2 de ago. de 2021, 13:46

    Hi Shivani,  When test classes execute(with seeAllData = false, which is the default behavior), all data records in 

    the org will not be accessible. This includes custom settings. So, when the triggers executes from within 

    your test class execution, it is not able to find the custom setting record for "ParentOpportunity" 

    (since that record is not created as test data within your testsetup method).   Since the trigger code is not validating whether the object returned from the statement below is null 

    before trying to access its field (ParentOppTriggerIsActive.isActive__), the error is being displayed. Hence, 

    the recommendation to insert the custom setting record pertaining to the value "ParentOpportunity" in 

    the "@testsetup" method in your test class.  

    Trigger_Handler__c ParentOppTriggerIsActive = Trigger_Handler__c.getValues('ParentOpportunity');

    if(ParentOppTriggerIsActive.isActive__c && UpdateCheckboxHandler.isFirstTime && ((trigger.isAfter && trigger.isinsert) || (trigger.isafter && trigger.isupdate))){

     Regards,  Sharath

0/9000

Hi, I am needing to verify how the DLRS Apex code factors into code coverage. We have a third party  app we purchased (not from the appexchange) that we are trying to deploy but it continually fails due to a lack of code coverage. The only non-managed packaged code we have in our org are 6 classes related to our DLRS. I am not much a developer so hoping to avoid having to update these test classes but right now looking to see if the DLRS could be me culprit.

 

Thanks

1 comentário
  1. 26 de mar. de 2021, 02:26
    It is a managed package but the Triggers are deployed as you not part of the managed package so trigger coverage is counted against your org. That said the triggers should be covered 100%.
0/9000

#SalesforceDaily Your Daily Tip - 29

 

#Trailblazer - Shiv Shankar

Category - Salesforce Apex

Tip - We should always try to leverage the concept of Mocking Framework while writing the test classes. With Mock we don't have to bother about Inserting the data in Test class and also it reduces duration of test class run. 

 

Submit your #Salesforce Tip!

https://lnkd.in/erh23RF

 

@Akash Mishra @Pritam Shekhawat @Vipul Goel 

#SalesforceOhana #Salesforce

 

Stay Safe!

0/9000
0/9000

Hi,

 

Can u explain me regarding Test classes as annotation @istTest(seeAlldData=false) as mentioning in a class and without mentioning it in class.

 

Thank u in advance.

3 comentários
0/9000