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
vignesh balasubramanian 14vignesh balasubramanian 14 

Test class is not covered the code

Hi Everyone, Following code is not covered in test class, kindly help me to make it works,
 
queryString = 'SELECT '; for(Schema.FieldSetMember relationshipField :SObjectType.npe4__Relationship__c.FieldSets.Relationship_Field_Set.getFields()) { queryString += relationshipField.getFieldPath()+','; } queryString = queryString .removeEnd(','); queryString += ' FROM npe4__Relationship__c WHERE npe4__Contact__c IN (' + contactIdFilter + ')';

    relationshipList= new List<relationshipWrapper>();
    relationshipWrapper rel;
    for(npe4__Relationship__c  currRec: Database.query(queryString) ){
        rel= new relationshipWrapper(currRec);
        relationshipList.add(rel);
    }

 
Glyn Anderson 3Glyn Anderson 3
Here's a refactor of the code:

<pre>
List<String> relationshipFields = new List<String>();
for ( Schema.FieldSetMember relationshipField :
        SObjectType.npe4__Relationship__c.FieldSets.Relationship_Field_Set.getFields() )
{
    relationshipFields.add( relationshipField.getFieldPath() );
}

queryString = String.join
(   new List<String>
    {   'SELECT'
    ,   String.join( relationshipFields, ',' )
    ,   'FROM npe4__Relationship__c'
    ,   'WHERE npe4__Contact__c IN (' + contactIdFilter + ')'
    }
,   ' '
);

relationshipList = new List<relationshipWrapper>();
for ( npe4__Relationship__c  currRec : (List<npe4__Relationship__c>) Database.query( queryString ) )
{
    relationshipList.add( new relationshipWrapper( currRec ) );
}
</pre>

To test this, there must be a field set on the npe4__Relationship__c object called "Relationship_Field_Set", and it must have at least one field in it.  This is metadata, so you can't create it in your test class.  It just has to exist.  Your test code must create a Contact record and a npe4__Relationship__c record that looks up to that Contact.  You don't show the code that creates "contactIdFilter", so I don't know how to set up the Contact to be included in the filter.  If you do this, both loops will execute at least once, and all of the code you posted should be covered.  Let me know if you have any more questions.
Glyn Anderson 3Glyn Anderson 3
Vignesh,  Did this answer solve your problem?  If so, please mark the question as "Solved".  If not, let me know - I'm happy to help more.  If you solved the problem another way, please post your solution for everyone's benefit.  Thanks!
Glyn Anderson 3Glyn Anderson 3
Vignesh,  Did you solve this problem?  If so, you can post your solution here and mark it as the Best Answer.  The community will appreciate it if you pick/post a Best Answer and mark the question as "Solved".  Thank you!