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
Jonathan Wolff 7Jonathan Wolff 7 

Create test class for campaign apex class

Hello, I tried to make a test class for my apex but I still get errors.
Could you give me some support:

Apex class
public class Kampagne_Brief{
    
    public string camId {get;set;}
    
    @InvocableMethod(Label = 'Kampagne_Brief' description='')  
    
    public static void Kampagne_Brief(List<Id> CampaignId) {
        
        string camName = [SELECT Id, Name FROM Campaign WHERE Id =: CampaignId.get(0) LIMIT 1].Name;
        String strDate = String.valueOf(System.now().dateGmt()); // FORMAT YYYY-MM-DD
        // String strDate = System.now().format('yyyyMMdd'); // FORMAT YYYYMMDD
        
        PageReference page = Page.Kampagne_Brief_PDF;
        
        page.getParameters().put('Id', CampaignId.get(0));
        
        string camId= page.getParameters().put('Id', CampaignId.get(0));
        // string camName = page.getParameters().put('Campaign.Name', CampaignId.get(0));
        Blob contentBlob = page.getContentAsPDF();
        
        ContentVersion cv = new ContentVersion();
        cv.VersionData = contentBlob;
        cv.Title = strDate + '_' + camName;
        //    cv.Title =  System.today().year() + '_' + System.today().month() + '_' + System.today().day() + '_' + 'Serienbrief_'+ camName;
        cv.PathOnClient =  strDate + '_' + camName + '.pdf';
        //    cv.PathOnClient =  System.today().year() + '_' + System.today().month()  + '_' + System.today().day() + '_' + 'Serienbrief.pdf';
        cv.Vertraulichkeitsstufe__c = 'Intern';
        cv.Dokumentenklasse__c ='Anderes Dokument (nicht aufbewahrungspflichtig)';
        insert cv;
        
        cv = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id LIMIT 1];
        
        ContentDocumentLink cdl = new ContentDocumentLink();
        cdl.ContentDocumentId = cv.ContentDocumentId;
        cdl.ShareType = 'I';
        cdl.LinkedEntityId = camId;
        insert cdl;
    }
}

My test class to this point:
I get the error message: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LinkedEntityId]: [LinkedEntityId]
 
@isTest 
public with sharing class Kampagnen_Brief_Test  {        
    static testmethod void contentDocumentTest()        {  
            
Campaign cam                        = new Campaign();
        cam.Name                            = 'Test Briefkampagne';
        cam.RecordTypeId                    = '0127a000001lOti';
        cam.IsActive                        = True;
        insert cam;

        
        ContentVersion cv = new ontentVersion();
        cv.Title = '2022-03-10_John Campaign';
        cv.PathOnClient = '2022-03-10_John Campaign.pdf';
        cv.VersionData = Blob.valueOf('Test Content');
        cv.IsMajorVersion = true;
        cv.Vertraulichkeitsstufe__c = 'Intern';
        cv.Dokumentenklasse__c ='Anderes Dokument (nicht aufbewahrungspflichtig)';
        Insert cv;
        ContentVersion contentVersion_2 = [SELECT Id, Title, ContentDocumentId 
                                           FROM ContentVersion WHERE Id = :cv.Id LIMIT 1];   
        ContentDocumentLink contentlink = new ContentDocumentLink();
        
        contentlink.contentdocumentid = contentVersion_2.contentdocumentid;
        contentlink.ShareType = 'V';
        insert contentlink;
        Kampagne_Brief KB = new Kampagne_Brief();             
        
    }
    
    
}

 
Best Answer chosen by Jonathan Wolff 7
CharuDuttCharuDutt
Hello Jonathan
Try Below Code
Small Change In You Class In Bold
public class Kampagne_Brief{
    
    public string camId {get;set;}
    
    @InvocableMethod(Label = 'Kampagne_Brief' description='')  
    
    public static void Kampagne_Brief(List<Id> CampaignId) {
        
        string camName = [SELECT Id, Name FROM Campaign WHERE Id =: CampaignId.get(0) LIMIT 1].Name;
        String strDate = String.valueOf(System.now().dateGmt()); // FORMAT YYYY-MM-DD
        // String strDate = System.now().format('yyyyMMdd'); // FORMAT YYYYMMDD
        
        PageReference page = Page.Kampagne_Brief_PDF;
        
        page.getParameters().put('Id', CampaignId.get(0));
        
        string camId= page.getParameters().put('Id', CampaignId.get(0));
        // string camName = page.getParameters().put('Campaign.Name', CampaignId.get(0));
        Blob contentBlob ;
        if(test.isRunningTest()){
            contentBlob = blob.valueOf('Test Data');
        }else{
        contentBlob = page.getContentAsPDF();
        }
        ContentVersion cv = new ContentVersion();
        
        cv.VersionData = contentBlob;
        cv.Title = strDate + '_' + camName;
        //    cv.Title =  System.today().year() + '_' + System.today().month() + '_' + System.today().day() + '_' + 'Serienbrief_'+ camName;
        cv.PathOnClient =  strDate + '_' + camName + '.pdf';
        //    cv.PathOnClient =  System.today().year() + '_' + System.today().month()  + '_' + System.today().day() + '_' + 'Serienbrief.pdf';
       // cv.Vertraulichkeitsstufe__c = 'Intern';
        //cv.Dokumentenklasse__c ='Anderes Dokument (nicht aufbewahrungspflichtig)';
        insert cv;
        
        cv = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id LIMIT 1];
        
        ContentDocumentLink cdl = new ContentDocumentLink();
        cdl.ContentDocumentId = cv.ContentDocumentId;
        cdl.ShareType = 'I';
        cdl.LinkedEntityId = camId;
        insert cdl;
    }
}


########################################################################


@isTest
public class Kampagne_BriefTest {
    @isTest
    public static void UnitTest(){
        Account acct = new Account (Name = 'Acme, Inc.');
        insert acct;
        system.debug('Inserted Account, ID: ' + acct.id);
        
        
        Contact con = new Contact(
            FirstName = 'Robin',
            LastName = 'Koehler',
            AccountId = acct.Id
        );
        insert con;
        Campaign camp = new Campaign(
            Name = 'Test',
            IsActive = TRUE
        );            
        insert camp;
        
        
        CampaignMember member = new CampaignMember(
            ContactId = con.Id,
            Status = 'sent',
            CampaignId = camp.Id
        );
        insert member;
        Kampagne_Brief.Kampagne_Brief(new list<Id>{Camp.Id});
    }
    
}
Please Mark It As Best Asnwer If It Helps
Thank You!

All Answers

CharuDuttCharuDutt
Hii Jonathan
Try Below test Class
@isTest
public class Kampagne_BriefTest {
    @isTest
    public static void UnitTest(){
        Account acct = new Account (Name = 'Acme, Inc.');
        insert acct;
        system.debug('Inserted Account, ID: ' + acct.id);
        
        Contact con = new Contact(
            FirstName = 'Robin',
            LastName = 'Koehler',
            AccountId = acct.Id
        );
        insert con;
        Campaign camp = new Campaign(
            Name = 'Test',
            IsActive = TRUE
        );            
        insert camp;
        
        
        CampaignMember member = new CampaignMember(
            ContactId = con.Id,
            Status = 'sent',
            CampaignId = camp.Id
        );
        insert member;
        Kampagne_Brief.Kampagne_Brief(new list<Id>{Camp.Id});
    }
    
}
Please Mark It As Best Asnwer If It Helps
Thank You!
Jonathan Wolff 7Jonathan Wolff 7
Hi CharuDutt, the sample was quite helpful. Now I get a coverage of 33%. Could you just tell me what I will need to insert to get the part below to be covered too?

User-added image
CharuDuttCharuDutt
Hii Jonathan Can you Please Give The Vfpage code As well so i'll try to cover the rest part
 
Jonathan Wolff 7Jonathan Wolff 7
Hi, yes absolutly. When I create a cv I need to assign the required values for Dokumentenklasse and Vertraulichkeitsstufe which are also mentioned in the apex just to inform you

The Visualforce ist
 
<apex:page standardController="Campaign" renderAs="pdf">
    <apex:form >      
        <apex:repeat value="{!Campaign.CampaignMembers}" var="cMem">
            <div style="page-break-after:always;">                
                <div style="text-align:right;">
                    <apex:image value="{!URLFOR($Resource.Allianz_Logo)}" width="200" height="50" />
                </div>        
                <br/>
                <br/>
                <header>
                    <h1 style="font-family: sans-serif; color: #808080; font-size: 16px; padding: 0px; ">Allianz Pension Partners GmbH</h1>
                </header>
                <div style="font-family: sans-serif; font-size: 14px">
                    {!cMem.CompanyOrAccount}<br/>
                    {!cMem.Name}<br/>
                    {!cMem.Street}<br/>
                    {!cMem.PostalCode} {!cMem.City}<br/>
                </div>                
                <br/>
                <br/>
                <table style="font-family: sans-serif; font-size: 14px">
                    <tr>
                        <td width="80">Datum: </td>
                        <td>{!DAY(Today())}. {!CASE(MONTH(Today()), 1, 'Januar', 2, 'Februar', 3, 'März', 4, 'April', 5, 'Mai', 6, 'Juni', 7, 'Juli', 8, 'August', 9, 'September', 10, 'Oktober', 11, 'November', 12, 'Dezember', 'Unknown')} {!YEAR(Today())} </td>
                    </tr>
                    <tr>
                        <td width="80">Name: </td>
                        <td>{!$User.FirstName} {!$User.LastName}</td>
                    </tr>
                    <tr>
                        <td width="80">Telefon: </td>
                        <td>{!$User.Phone}</td>
                    </tr>
                    <tr>
                        <td width="80">E-Mail: </td>
                        <td>{!$User.Email}</td>
                    </tr>                
                </table>
                <br/>
                <br/>
                <h2 style="font-family: sans-serif; font-size: 14px"><b>Herzlich willkommen bei Allianz Pension Partners GmbH</b></h2><br/>
                <div style="display: block; font-family: sans-serif; font-size: 14px; height: 435px;"> 
                    Sehr geehrte/r {!cMem.Salutation} {!cMem.LastName}<br/> 
                    
   
                    
                   <apex:outputText escape="false" value="{!SUBSTITUTE(Campaign.Serienbrief_Inhalt__c, '__NAME__', cMem.Name)}" />
                    
                    
                         
                </div> 
                
                
                
            </div>
        </apex:repeat>
    </apex:form>   
</apex:page>

 
CharuDuttCharuDutt
Hello Jonathan
Try Below Code
Small Change In You Class In Bold
public class Kampagne_Brief{
    
    public string camId {get;set;}
    
    @InvocableMethod(Label = 'Kampagne_Brief' description='')  
    
    public static void Kampagne_Brief(List<Id> CampaignId) {
        
        string camName = [SELECT Id, Name FROM Campaign WHERE Id =: CampaignId.get(0) LIMIT 1].Name;
        String strDate = String.valueOf(System.now().dateGmt()); // FORMAT YYYY-MM-DD
        // String strDate = System.now().format('yyyyMMdd'); // FORMAT YYYYMMDD
        
        PageReference page = Page.Kampagne_Brief_PDF;
        
        page.getParameters().put('Id', CampaignId.get(0));
        
        string camId= page.getParameters().put('Id', CampaignId.get(0));
        // string camName = page.getParameters().put('Campaign.Name', CampaignId.get(0));
        Blob contentBlob ;
        if(test.isRunningTest()){
            contentBlob = blob.valueOf('Test Data');
        }else{
        contentBlob = page.getContentAsPDF();
        }
        ContentVersion cv = new ContentVersion();
        
        cv.VersionData = contentBlob;
        cv.Title = strDate + '_' + camName;
        //    cv.Title =  System.today().year() + '_' + System.today().month() + '_' + System.today().day() + '_' + 'Serienbrief_'+ camName;
        cv.PathOnClient =  strDate + '_' + camName + '.pdf';
        //    cv.PathOnClient =  System.today().year() + '_' + System.today().month()  + '_' + System.today().day() + '_' + 'Serienbrief.pdf';
       // cv.Vertraulichkeitsstufe__c = 'Intern';
        //cv.Dokumentenklasse__c ='Anderes Dokument (nicht aufbewahrungspflichtig)';
        insert cv;
        
        cv = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id LIMIT 1];
        
        ContentDocumentLink cdl = new ContentDocumentLink();
        cdl.ContentDocumentId = cv.ContentDocumentId;
        cdl.ShareType = 'I';
        cdl.LinkedEntityId = camId;
        insert cdl;
    }
}


########################################################################


@isTest
public class Kampagne_BriefTest {
    @isTest
    public static void UnitTest(){
        Account acct = new Account (Name = 'Acme, Inc.');
        insert acct;
        system.debug('Inserted Account, ID: ' + acct.id);
        
        
        Contact con = new Contact(
            FirstName = 'Robin',
            LastName = 'Koehler',
            AccountId = acct.Id
        );
        insert con;
        Campaign camp = new Campaign(
            Name = 'Test',
            IsActive = TRUE
        );            
        insert camp;
        
        
        CampaignMember member = new CampaignMember(
            ContactId = con.Id,
            Status = 'sent',
            CampaignId = camp.Id
        );
        insert member;
        Kampagne_Brief.Kampagne_Brief(new list<Id>{Camp.Id});
    }
    
}
Please Mark It As Best Asnwer If It Helps
Thank You!
This was selected as the best answer
Jonathan Wolff 7Jonathan Wolff 7
Thank you so muc! Its working :)