• Apex developer 21
  • NEWBIE
  • 140 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 24
    Questions
  • 14
    Replies
Can anyone help me where and how to start with writing a testclass for the following example?
public with sharing class AccountTree{

    public String currentId;
    public List<ObjectStructureMap> asm ;
    public Map<String, ObjectStructureMap> masm;
    public List<Integer> maxLevel;
    
    public AccountTree() {
        this.asm = new List<ObjectStructureMap>{};
        this.masm = new Map<String, ObjectStructureMap>{};
        this.maxLevel = new List<Integer>{};
    }
    
    public void setcurrentId( String cid ){
        currentId = cid;
    }

    public List<ObjectStructureMap> getObjectStructure(){
        asm.clear();
        if ( currentId == null ) {
            currentId = System.currentPageReference().getParameters().get( 'id' );
        }
        
        System.assertNotEquals( currentId, null, 'sObject ID must be provided' );
        asm = formatObjectStructure( CurrentId );
        
        return asm;
    }

    public ObjectStructureMap[] formatObjectStructure( String currentId ){
    
        List<ObjectStructureMap> asm = new List<ObjectStructureMap>{};
        masm.clear();

        List<Account> al            = new List<Account>{};
        List<ID> currentParent      = new List<ID>{};
        Map<ID, String> nodeList    = new Map<ID, String>{};
        List<String> nodeSortList   = new List<String>{};
        List<Boolean> levelFlag     = new List<Boolean>{};
        List<Boolean> closeFlag     = new List<Boolean>{};
        String nodeId               = '0';
        String nodeType             = 'child';
        Integer count               = 0;
        Integer level               = 0;
        Boolean endOfStructure      = false;
        
        currentParent.add( GetTopElement( currentId ) );

        while ( !endOfStructure ){

            if( level == 0 ){
                //Change below     
                al = [ SELECT a.Type, a.Site, a.ParentId, a.OwnerId, a.Name, a.Industry, a.Id FROM Account a WHERE a.id IN : CurrentParent ORDER BY a.Name ];
            } 
            else {
                //Change below      
                al = [ SELECT a.Type, a.Site, a.ParentId, a.OwnerId, a.Name, a.Industry, a.Id FROM Account a WHERE a.ParentID IN : CurrentParent ORDER BY a.Name ];
            }

            if( al.size() == 0 ){
                endOfStructure = true;
            }
            else{
                currentParent.clear();
                for ( Integer i = 0 ; i < al.size(); i++ ){
                    //Change below
                    Account a = al[i];
                    nodeId = ( level > 0 ) ? NodeList.get( a.ParentId )+'.'+String.valueOf( i ) : String.valueOf( i );
                    masm.put( NodeID, new ObjectStructureMap( nodeID, levelFlag, closeFlag, nodeType, false, false, a ) );
                    currentParent.add( a.id );
                    nodeList.put( a.id,nodeId );
                    nodeSortList.add( nodeId );
                }
                
                maxLevel.add( level );                
                level++;
            }
        }
        
        NodeSortList.sort();
        for( Integer i = 0; i < NodeSortList.size(); i++ ){
            List<String> pnl = new List<String> {};
            List<String> cnl = new List<String> {};
            List<String> nnl = new List<String> {};
            
            if ( i > 0 ){
                String pn   = NodeSortList[i-1];
                pnl         = pn.split( '\\.', -1 );
            }

            String cn   = NodeSortList[i];
            cnl         = cn.split( '\\.', -1 );

            if( i < NodeSortList.size()-1 ){
                String nn = NodeSortList[i+1];
                nnl = nn.split( '\\.', -1 );
            }
            
            ObjectStructureMap tasm = masm.get( cn );
            if ( cnl.size() < nnl.size() ){
                //Parent
                tasm.nodeType = ( isLastNode( cnl ) ) ? 'parent_end' : 'parent';
            }
            else if( cnl.size() > nnl.size() ){
                tasm.nodeType   = 'child_end';
                tasm.closeFlag  = setcloseFlag( cnl, nnl, tasm.nodeType );
            }
            else{
                tasm.nodeType = 'child';
            }
            
            tasm.levelFlag = setlevelFlag( cnl, tasm.nodeType ); 
            
            //Change below
            if ( tasm.account.id == currentId ) {
                tasm.currentNode = true;
            }
            asm.add( tasm );
        }
        
        asm[0].nodeType             = 'start';
        asm[asm.size()-1].nodeType  = 'end';
        
        return asm;
    }
    
    public List<Boolean> setlevelFlag( List<String> nodeElements, String nodeType ){
        
        List<Boolean> flagList = new List<Boolean>{};
        String searchNode   = '';
        String workNode     = '';
        Integer cn          = 0;
        
        for( Integer i = 0; i < nodeElements.size() - 1; i++ ){
            cn = Integer.valueOf( nodeElements[i] );
            cn++;
            searchNode  = workNode + String.valueOf( cn );
            workNode    = workNode + nodeElements[i] + '.';
            if ( masm.containsKey( searchNode ) ){
                flagList.add( true );
            }
            else {
                flagList.add( false );
            }
        }
        
        return flagList;
    }
    
    public List<Boolean> setcloseFlag( List<String> cnl, List<String> nnl, String nodeType ){
        
        List<Boolean> flagList = new List<Boolean>{};
        String searchNode   = '';
        String workNode     = '';
        Integer cn          = 0;
        
        for( Integer i = nnl.size(); i < cnl.size(); i++ ){
            flagList.add( true );
        }
        
        return flagList;
    }
    
    public Boolean isLastNode( List<String> nodeElements ){
        
        String searchNode   = '';
        Integer cn          = 0;
        
        for( Integer i = 0; i < nodeElements.size(); i++ ){
            if ( i == nodeElements.size()-1 ){
                cn = Integer.valueOf( nodeElements[i] );
                cn++;
                searchNode = searchNode + String.valueOf( cn );
            }
            else {
                searchNode = searchNode + nodeElements[i] + '.';
            }
        }
        if ( masm.containsKey( searchNode ) ){
            return false;
        }
        else{
            return true;
        }
    }
    
    public String GetTopElement( String objId ){
        
        Boolean top = false;
        while ( !top ) {
            //Change below
            Account a = [ Select a.Id, a.ParentId From Account a where a.Id =: objId limit 1 ];
            
            if ( a.ParentID != null ) {
                objId = a.ParentID;
            }
            else {
                top = true;
            }
        }
        return objId ;
    }
    
    public with sharing class ObjectStructureMap{

        public String nodeId;
        public Boolean[] levelFlag = new Boolean[]{};
        public Boolean[] closeFlag = new Boolean[]{};
        public String nodeType;
        public Boolean currentNode;
        
        public Account account;
        
        public String getnodeId() { return nodeId; }
        public Boolean[] getlevelFlag() { return levelFlag; }
        public Boolean[] getcloseFlag() { return closeFlag; }
        public String getnodeType() { return nodeType; }
        public Boolean getcurrentNode() { return currentNode; }

        public Account getaccount() { return account; }
        
        public void setnodeId( String n ) { this.nodeId = n; }
        public void setlevelFlag( Boolean l ) { this.levelFlag.add(l); }
        public void setlcloseFlag( Boolean l ) { this.closeFlag.add(l); }
        public void setnodeType( String nt ) { this.nodeType = nt; }
        public void setcurrentNode( Boolean cn ) { this.currentNode = cn; }

        public void setaccount( Account a ) { this.account = a; }

        public ObjectStructureMap( String nodeId, Boolean[] levelFlag,Boolean[] closeFlag , String nodeType, Boolean lastNode, Boolean currentNode, Account a ){
            
            this.nodeId         = nodeId;
            this.levelFlag      = levelFlag; 
            this.closeFlag      = closeFlag;
            this.nodeType       = nodeType;
            this.currentNode    = currentNode;

            this.account = a;
        }
    }
}

 
Can anyone point me in the right direction if its possible to get object values form a .net website into salesforce. If there are articles which explain this topic and if it possible in 2 directions for example with SOAP?
public class CreateInvoice{
    
    public CreateInvoice(){
        
        List<Training__c> trainingList = new List<Training__c>();
        List<Facturatie__c> facturatieList = new List<Facturatie__c>();
        
        try {
        trainingList = [SELECT id , NAME, Startdatum__c,factuur_bedrijf__c,
                          (SELECT Cursist_Prijs__c, Training__c, Cursist__c,CreatedDate,Prijs_training__c,
                           korting__c,Id 
                           FROM Trainingen_Volgen__r ) 
                       FROM  Training__c 
                       WHERE id NOT IN (SELECT  Training__c FROM Facturatie__c)];
        }catch (Exception e) {
            System.debug('The following exception has occurred' + e.getMessage() +
                         'At line number :' + e.getLineNumber() + 'Error' +
                         e.getStackTraceString());
        }              
        if(!trainingList.IsEmpty()){
            
            for(Training__c trainingRecord : trainingList){
                
                if(!trainingRecord.Trainingen_Volgen__r.IsEmpty()){
                    
                    for(Cursist__c cursistRecord : trainingRecord.Trainingen_Volgen__r){
                        
                        Facturatie__c facturatieRecord = checkDate(cursistRecord,trainingRecord);
                        facturatieList.add(facturatieRecord);
                    }
                }   
            }

            if(!facturatieList.IsEmpty()){  
               try {
                   insert facturatieList;
                }catch (Exception e) {
                    System.debug('The following exception has occurred' + e.getMessage() +
                                 'At line number :' + e.getLineNumber() + 'Error' +
                                 e.getStackTraceString());
                }   
               
            }
        }   
    }
    
    public Facturatie__c checkDate(Cursist__c cursistRecord,Training__c trainingRecord){
        
        if(cursistRecord != null && trainingRecord != null){
            Date todaysDate = system.today();
            
            if( todaysDate.addDays(-21) >= trainingRecord.Startdatum__c 
                && todaysDate >= cursistRecord.CreatedDate 
                && todaysDate.addDays(-1) >= trainingRecord.Startdatum__c){
                
                Facturatie__c facturatieRecord = new Facturatie__c();
                
                facturatieRecord.Training__c = trainingRecord.Id;   
                facturatieRecord.Factuur_Datum__c = todaysDate;  
                facturatieRecord.Verval_datum__c = todaysDate.addDays(30);
                
                if(cursistRecord.Prijs_training__c != null &&  cursistRecord.korting__c != null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.Prijs_training__c - cursistRecord.korting__c;
                }else if(cursistRecord.Prijs_training__c != null && cursistRecord.korting__c == null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.Prijs_training__c;
                }else if(cursistRecord.Prijs_training__c == null && cursistRecord.korting__c != null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.korting__c ;
                }
                
                facturatieRecord.Korting__c =  cursistRecord.korting__c;
                facturatieRecord.cursist_prijs__c= cursistRecord.Cursist_Prijs__c ;
                facturatieRecord.Contactpersoon__c = cursistRecord.Cursist__c;
                facturatieRecord.Account__c = trainingRecord.factuur_bedrijf__c; 
                
                return facturatieRecord;
            }
        }
        
        return null;
    }
}
 
@isTest
public class CreateInvoiceTestClass{
    
    // Creating Test Data
   @isTest public static void testData(){
    
        Account account = new Account(Name = 'TestAccount1');  
        insert account;
        
        List<Training__c> trainingList = new List<Training__c>();
        for(integer counter=0;counter<20;counter++){
            
            Training__c trainingRecord = new Training__c();
            trainingRecord.name = 'TestRecord'+counter;
            trainingRecord.Startdatum__c = System.today().addDays(+2);
            trainingRecord.factuur_bedrijf__c = account.Id;
            trainingList.add(trainingRecord);
        }
        insert trainingList;
        
         List<Facturatie__c> facturatieList = new List<Facturatie__c>();
        for(integer counter=0;counter<20;counter++){
            
            Facturatie__c facturatieRecord = new Facturatie__c();
            facturatieRecord.name = 'TestRecord'+counter;
            facturatieRecord.Factuur_Bedrag__c = 1000;
            facturatieRecord.Training__c = trainingList[counter].Id;
            facturatieList.add(facturatieRecord);
        }

       for(integer counter=0;counter<20;counter++){
            
            Facturatie__c facturatieRecord = new Facturatie__c();
            facturatieRecord.name = 'TestRecord2'+counter;
            facturatieRecord.Factuur_Bedrag__c = 1000;
            facturatieRecord.Training__c = trainingList[counter].Id;
            facturatieList.add(facturatieRecord);
        }
  
       insert facturatieList;

       
        List<Cursist__c> cursistList = new List<Cursist__c>();
        for(integer counter=0;counter<20;counter++){
            
            Cursist__c cursistRecord = new Cursist__c();           
            cursistRecord.Training__c = trainingList[counter].Id;
            cursistRecord.Prijs_training__c = 10;
            cursistRecord.korting__c = 10;
            cursistRecord.CreatedDate = System.today();
            cursistList.add(cursistRecord);
        }
        insert cursistList;
       
       system.debug(facturatieList[0].Account__c);
       Test.StartTEst();
	   CreateInvoice createInv = new CreateInvoice();
	   Test.stopTest();
      
       System.assertEquals(facturatieList[0].Account__c,null);
       
    }
   
}

User-added image
How do i write a unittest for the email class. I attached my code below:
public class SendemailController {
public String OpportunityId {get;set;}

Public SendemailController(){
OpportunityId = ApexPages.currentPage().getParameters().get('Id');
}

Public Pagereference sendEmailFunction(){
Opportunity getEmail = [SELECT Id, Contact__r.email FROM Opportunity WHERE id=:OpportunityId];
   if(getEmail.Contact__r.email != null) {
     String toaddress = getEmail.Contact__r.email;

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {toaddress};
String[] ccAddresses = new String[] {toaddress};
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
mail.setReplyTo(toaddress);
mail.setSenderDisplayName('Name');
mail.setSubject('Testing email through apex');
mail.setBccSender(false);
mail.setUseSignature(true);
mail.setPlainTextBody('Dear tester, here are the attechments. This mail is sent trough apex');

List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();        
for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :OpportunityId]){
   Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
   efa.setFileName(a.Name);
   efa.setBody(a.Body);
   fileAttachments.add(efa);
}    

mail.setFileAttachments(fileAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
  PageReference reference = new PageReference('https://eu11.salesforce.com/'+ OpportunityId);
  reference.setRedirect(true);
  return reference;
  }
}
I get the error written in the title. When i add <apex:form></apex:form> tags it gives the error: Error: <messaging:emailTemplate> cannot contain <apex:form>.   So im stuck in a loop. Could someon help me out. Here is my VF email template, class and componet:
<messaging:emailtemplate recipienttype="contact" subject="Product Enquiry">
  <messaging:htmlemailbody > 
     Congratulations!
     This is your new Visualforce Email Template. Following are a list of randomly choosen accounts in my org:
    <!-- Embedding visualforce component here -->
    <c:emailcontroller >
  </c:emailcontroller></messaging:htmlemailbody> 
</messaging:emailtemplate>
 
<apex:component access="global" controller="SendemailController" >

<script type="text/javascript">
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener('load',init,true)
else
window.attachEvent('onload',init)
</script>
<apex:form>
<apex:actionFunction name="sendEmail" action="{!sendEmailFunction}">
</apex:actionFunction>
</apex:form>
</apex:component>
 
public class SendemailController {
public String AttachmentId {get;set;}

Public SendemailController(){
AttachmentId = ApexPages.currentPage().getParameters().get('Id');
system.debug('Attachment id->'+AttachmentId );
}

Public Pagereference sendEmailFunction(){
Attachment getEmail = [SELECT Id,Name,ContentType FROM Attachment where ParentId ='0Q00Y000000LIVL' LIMIT 1];
if(getEmail.Id != null) {
String toaddress = 'info@test.com';
system.debug(toaddress);

try {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {toaddress};
String[] ccAddresses = new String[] {'info@test.com'};
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
mail.setReplyTo(toaddress);
mail.setSenderDisplayName('You have don it');
mail.setSubject('Testing email through apex');
mail.setBccSender(false);
mail.setUseSignature(true);
mail.setPlainTextBody('This is test email body. This mail is being sent from apex code');
//mail.setHtmlBody('<b> This is HTML body </b>' );

List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = '0Q00Y000000LIVL']){
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(a.Name);
efa.setBody(a.Body);
fileAttachments.add(efa);
//mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
}
mail.setFileAttachments(fileAttachments);

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

} catch(Exception e) {}
}

PageReference reference = new PageReference('https://eu11.salesforce.com/'+AttachmentId);
reference.setRedirect(true);
return reference;
}

}

 
Is it possible to call an apex class directly from visual force email template to execute some tasks? 
I have this visualforce emailtemplate where i can send the attachments on quotes as a link but the receiver needs to be logged in. How do i manage this whitout a login. Or can i send the body of the attachment with the mail. Here is my code:
<messaging:emailTemplate recipientType="Contact"
    relatedToType="Quote"
    subject="Attachment for Quote: {!relatedTo.name}"
    replyTo="test@test.nl">

    <messaging:htmlEmailBody >
        <html>
            <body>
            <p>Dear {!recipient.name},</p>
            <p>Quote</p>
            <center>
             <p>..   ..</p>
            </center>
        <br/>
        <apex:repeat var="cx" value="{!relatedTo.Attachments}">
          <a href="{!URLFOR($Action.Attachment.Download, cx.Id)}" target="_blank" styleClass="btn">Download {!cx.Name}</a>
        <br/>
        </apex:repeat>
            </body>
        </html>
    </messaging:htmlEmailBody>
</messaging:emailTemplate>

 
Can someone give an example how to attach attachments form Quotes to a visualforce email template so that an external receiver kan download the attachments. I have seen many examples but they all require the recever to login to be able to download the. I have found the following example but dont know how to apply this for a visualforce emailtemplate on quotes as a newbie see:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'user@dimain.com'};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('user@domain.com');
        mail.setSenderDisplayName('SFDC Support');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setTargetObjectId('005Q0000000Fo7f');
       // Give visualforce template id
        mail.setTemplateId('00XQ0000000iULj');
        mail.saveAsActivity = false;    
        
      //Set email file attachments
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :oppr])
        {
     // Add to attachment file list
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        efa.setFileName(a.Name);
        efa.setBody(a.Body);
        fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);

      //Send email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

 
<apex:page standardController="Opportunity" extensions="email_class">
    <apex:form >
           
        <apex:pageBlock title="Email Details">
        
            <apex:pageBlock title="Reciepient">
                <b>TO: </b><br/><apex:inputText value="{!emailTo}"/><p/>
                <b>CC: </b><br/><apex:inputText value="{!emailCC}"/><br/>
                <br/>
                <b>Subject: </b><br/><apex:inputText value="{!subject}" maxlength="200"/><br/>
                <br/>
                <b>Body: </b><br/><apex:inputTextArea value="{!email_body}" rows="10" cols="100"/>
            </apex:pageBlock>          
                    
     <apex:pageBlock title="Attachments">
        <apex:pageBlockTable value="{!Attachments}" var="wrap">
            <apex:column headerValue="Select">
                <apex:inputCheckbox value="{!wrap.selected }"/>
            </apex:column>
       
       <apex:column value="{!wrap.name}"/>
      
       </apex:pageBlockTable><p/>
       </apex:pageblock>
                
       <apex:commandButton value="Send Email" action="{!send}"/>
       <apex:commandButton value="Canel" action="{!cancel}"/>
            
       </apex:pageBlock>
                           
    </apex:form>    
</apex:page>
public class email_class
{
    
    Public string ToAddresses {get;set;}
    Public string CCAddresses {get;set;}
    Public string opportunityId {get;set;}
    Public string subject {get;set;}
    public string email_body {get;set;}
    public string emailTo {get;set;}
    public string emailCC {get;set;}
    
    public class Attachmentwrapper
    {
        public Attachment acc{get; set;}
        public Boolean selected {get; set;}
        public Attachmentwrapper(Attachment a)
        {
            acc = new Attachment();
            acc = a;
        }
    }
    
               
    public email_class(ApexPages.StandardController controller) {
        opportunityId = ApexPages.currentPage().getParameters().get('id');
    }
    
     List<Attachmentwrapper> AttachmentList = new List<Attachmentwrapper>();
     List<Attachment> selectedAttachments = new List<Attachment>();
       
        public List<Attachmentwrapper> getAttachments()
        {
            for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :opportunityId])
            {      
                AttachmentList.add(new Attachmentwrapper(a));
            }
            return AttachmentList;
        }
    
    Public PageReference send()
    {
  
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // set the to address
        mail.setToAddresses(new String[] {emailTo});
        string [] ccaddress;
            if(emailCC != null && emailCC.trim() != ''){
            ccaddress = emailCC.split(',',0);
            mail.setCcAddresses(ccaddress);
            }
        mail.setSubject(subject);
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setPlainTextBody(email_body);
        mail.setWhatId(opportunityId);// Set email file attachments 

        selectedAttachments.clear();
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for(Attachmentwrapper accwrapper : AttachmentList){
        if(accwrapper.selected == true){
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        efa.setFileName(accwrapper.acc.Name);
        efa.setBody(accwrapper.acc.Body);
        fileAttachments.add(efa);
        }
        
        if(!(fileAttachments.isempty()))
            mail.setFileAttachments(fileAttachments);
       
         selectedAttachments.add(accwrapper.acc);
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
       }  
        
        PageReference pageRef = new PageReference('/' + opportunityId);
        pageRef.setRedirect(true);
        return pageRef;
        } 
}


 
public class CreateInvoice{
    
    public CreateInvoice(){
        
        List<Training__c> trainingList = new List<Training__c>();
        List<Facturatie__c> facturatieList = new List<Facturatie__c>();
        
        try {
        trainingList = [SELECT id , NAME, Startdatum__c,factuur_bedrijf__c,
                          (SELECT Cursist_Prijs__c, Training__c, Cursist__c,CreatedDate,Prijs_training__c,
                           korting__c,Id 
                           FROM Trainingen_Volgen__r ) 
                       FROM  Training__c 
                       WHERE id NOT IN (SELECT  Training__c FROM Facturatie__c)];
        }catch (Exception e) {
            System.debug('The following exception has occurred' + e.getMessage() +
                         'At line number :' + e.getLineNumber() + 'Error' +
                         e.getStackTraceString());
        }              
        if(!trainingList.IsEmpty()){
            
            for(Training__c trainingRecord : trainingList){
                
                if(!trainingRecord.Trainingen_Volgen__r.IsEmpty()){
                    
                    for(Cursist__c cursistRecord : trainingRecord.Trainingen_Volgen__r){
                        
                        Facturatie__c facturatieRecord = checkDate(cursistRecord,trainingRecord);
                        facturatieList.add(facturatieRecord);
                    }
                }   
            }

            if(!facturatieList.IsEmpty()){  
               try {
                   insert facturatieList;
                }catch (Exception e) {
                    System.debug('The following exception has occurred' + e.getMessage() +
                                 'At line number :' + e.getLineNumber() + 'Error' +
                                 e.getStackTraceString());
                }   
               
            }
        }   
    }
    
    public Facturatie__c checkDate(Cursist__c cursistRecord,Training__c trainingRecord){
        
        if(cursistRecord != null && trainingRecord != null){
            Date todaysDate = system.today();
            
            if( todaysDate.addDays(-21) >= trainingRecord.Startdatum__c 
                && todaysDate >= cursistRecord.CreatedDate 
                && todaysDate.addDays(-1) >= trainingRecord.Startdatum__c){
                
                Facturatie__c facturatieRecord = new Facturatie__c();
                
                facturatieRecord.Training__c = trainingRecord.Id;   
                facturatieRecord.Factuur_Datum__c = todaysDate;  
                facturatieRecord.Verval_datum__c = todaysDate.addDays(30);
                
                if(cursistRecord.Prijs_training__c != null &&  cursistRecord.korting__c != null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.Prijs_training__c - cursistRecord.korting__c;
                }else if(cursistRecord.Prijs_training__c != null && cursistRecord.korting__c == null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.Prijs_training__c;
                }else if(cursistRecord.Prijs_training__c == null && cursistRecord.korting__c != null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.korting__c ;
                }
                
                facturatieRecord.Korting__c =  cursistRecord.korting__c;
                facturatieRecord.cursist_prijs__c= cursistRecord.Cursist_Prijs__c ;
                facturatieRecord.Contactpersoon__c = cursistRecord.Cursist__c;
                facturatieRecord.Account__c = trainingRecord.factuur_bedrijf__c; 
                
                return facturatieRecord;
            }
        }
        
        return null;
    }
}
 
@isTest
public class CreateInvoiceTestClass{
    
    // Creating Test Data
   @isTest public static void testData(){
    
        Account account = new Account(Name = 'TestAccount1');  
        insert account;
        
        List<Training__c> trainingList = new List<Training__c>();
        for(integer counter=0;counter<200;counter++){
            
            Training__c trainingRecord = new Training__c();
            trainingRecord.name = 'TestRecord'+counter;
            trainingRecord.Startdatum__c = System.today().addDays(+2);
            trainingRecord.factuur_bedrijf__c = account.Id;
            trainingList.add(trainingRecord);
        }
        insert trainingList;
        
         List<Facturatie__c> facturatieList = new List<Facturatie__c>();
        for(integer counter=0;counter<200;counter++){
            
            Facturatie__c facturatieRecord = new Facturatie__c();
            facturatieRecord.name = 'TestRecord'+counter;
            facturatieRecord.Factuur_Bedrag__c = 1000;
            facturatieRecord.Training__c = trainingList[counter].Id;
            facturatieList.add(facturatieRecord);
        }
        insert facturatieList;

       
        List<Cursist__c> cursistList = new List<Cursist__c>();
        for(integer counter=0;counter<200;counter++){
            
            Cursist__c cursistRecord = new Cursist__c();           
            cursistRecord.Training__c = trainingList[counter].Id;
            cursistRecord.Prijs_training__c = 10;
            cursistRecord.korting__c = 10;
            cursistRecord.CreatedDate = System.today();
            cursistList.add(cursistRecord);
        }
        insert cursistList;
       
       system.debug(facturatieList[0].Account__c);
       Test.StartTEst();
	   CreateInvoice createInv = new CreateInvoice();
	   Test.stopTest();
      
       System.assertEquals(facturatieList[0].Account__c,null);
       
    }
   
}
User-added image
 
Im trying to make a unittest for my class but it gives me 0 coverage, please some help:
public class CreateInvoice{
    
    public CreateInvoice(){
        
        List<Training__c> trainingList = new List<Training__c>();
        List<Facturatie__c> facturatieList = new List<Facturatie__c>();
        
        try {
        trainingList = [SELECT id , NAME, Startdatum__c,factuur_bedrijf__c,
                          (SELECT Cursist_Prijs__c, Training__c, Cursist__c,CreatedDate,Prijs_training__c,
                           korting__c,Id 
                           FROM Trainingen_Volgen__r ) 
                       FROM  Training__c 
                       WHERE id NOT IN (SELECT  Training__c FROM Facturatie__c)];
        }catch (Exception e) {
            System.debug('The following exception has occurred' + e.getMessage() +
                         'At line number :' + e.getLineNumber() + 'Error' +
                         e.getStackTraceString());
        }              
        if(!trainingList.IsEmpty()){
            
            for(Training__c trainingRecord : trainingList){
                
                if(!trainingRecord.Trainingen_Volgen__r.IsEmpty()){
                    
                    for(Cursist__c cursistRecord : trainingRecord.Trainingen_Volgen__r){
                        
                        Facturatie__c facturatieRecord = checkDate(cursistRecord,trainingRecord);
                        facturatieList.add(facturatieRecord);
                    }
                }   
            }

            if(!facturatieList.IsEmpty()){  
               try {
                   insert facturatieList;
                }catch (Exception e) {
                    System.debug('The following exception has occurred' + e.getMessage() +
                                 'At line number :' + e.getLineNumber() + 'Error' +
                                 e.getStackTraceString());
                }   
               
            }
        }   
    }
    
    public Facturatie__c checkDate(Cursist__c cursistRecord,Training__c trainingRecord){
        
        if(cursistRecord != null && trainingRecord != null){
            Date todaysDate = system.today();
            
            if( todaysDate.addDays(-21) >= trainingRecord.Startdatum__c 
                && todaysDate >= cursistRecord.CreatedDate 
                && todaysDate.addDays(-1) >= trainingRecord.Startdatum__c){
                
                Facturatie__c facturatieRecord = new Facturatie__c();
                
                facturatieRecord.Training__c = trainingRecord.Id;   
                facturatieRecord.Factuur_Datum__c = todaysDate;  
                facturatieRecord.Verval_datum__c = todaysDate.addDays(30);
                
                if(cursistRecord.Prijs_training__c != null &&  cursistRecord.korting__c != null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.Prijs_training__c - cursistRecord.korting__c;
                }else if(cursistRecord.Prijs_training__c != null && cursistRecord.korting__c == null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.Prijs_training__c;
                }else if(cursistRecord.Prijs_training__c == null && cursistRecord.korting__c != null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.korting__c ;
                }
                
                facturatieRecord.Korting__c =  cursistRecord.korting__c;
                facturatieRecord.cursist_prijs__c= cursistRecord.Cursist_Prijs__c ;
                facturatieRecord.Contactpersoon__c = cursistRecord.Cursist__c;
                facturatieRecord.Account__c = trainingRecord.factuur_bedrijf__c; 
                
                return facturatieRecord;
            }
        }
        
        return null;
    }
}
 
@isTest
public class CreateInvoiceTestClass{
    
    // Creating Test Data
   @isTest public static void testData(){
    
        Account account = new Account(Name = 'TestAccount1');  
        insert account;
        
        List<Training__c> trainingList = new List<Training__c>();
        for(integer counter=0;counter<200;counter++){
            
            Training__c trainingRecord = new Training__c();
            trainingRecord.name = 'TestRecord'+counter;
            trainingRecord.Startdatum__c = System.today().addDays(+2);
            trainingRecord.factuur_bedrijf__c = account.Id;
            trainingList.add(trainingRecord);
        }
        insert trainingList;
        
         List<Facturatie__c> facturatieList = new List<Facturatie__c>();
        for(integer counter=0;counter<200;counter++){
            
            Facturatie__c facturatieRecord = new Facturatie__c();
            facturatieRecord.name = 'TestRecord'+counter;
            facturatieRecord.Factuur_Bedrag__c = 1000;
            facturatieRecord.Training__c = trainingList[counter].Id;
            facturatieList.add(facturatieRecord);
        }
        insert facturatieList;

       
        List<Cursist__c> cursistList = new List<Cursist__c>();
        for(integer counter=0;counter<200;counter++){
            
            Cursist__c cursistRecord = new Cursist__c();           
            cursistRecord.Training__c = trainingList[counter].Id;
            cursistRecord.Prijs_training__c = 10;
            cursistRecord.korting__c = 10;
            cursistRecord.CreatedDate = System.today();
            cursistList.add(cursistRecord);
        }
        insert cursistList;
       
      system.debug(facturatieList[0].Account__c);
       
      
       System.assertEquals(facturatieList[0].Account__c,null);
       
    }
   
}

 
public class BatchDossierInvoice implements Database.Batchable<sObject>,Schedulable  {

    public void execute(SchedulableContext SC) {
       Database.executeBatch(new BatchDossierInvoice(), 200); 
    }

    public Database.QueryLocator start(Database.BatchableContext info){
system.debug('line 3');  
     try{
       
                    String query = 'SELECT Id ,(SELECT Id , Betaald_max__c ,Betaald__c,Partij__c,Partij__r.AccountId '+
                                    'FROM Partijen__r ORDER BY Betaald__c DESC ), '+
                                    '(SELECT Id , Dossier__c,Totaal_Merlijn__c '+
                                    'FROM Declaraties__r) '+
                        'FROM Dossier__c '+
                        'WHERE Id IN (SELECT Dossier__c FROM Declaratie__c) '+
                        'AND createddate >= LAST_N_DAYS:30';
         
         
     
         return Database.getQueryLocator(query); 
         system.debug(query);
         
        }catch(Exception e ){
         
            System.debug('The following exception has occurred' + e.getMessage());
        } 
        return null;                    
    }
   
    public void execute(Database.BatchableContext bc, List<Dossier__c> dossierList){     
        
        if(!dossierList.IsEmpty() && dossierList != null){
            List<Facturatie__c> facturatieList = new List<Facturatie__c>();    
            
            for(Dossier__c dossierRecord : dossierList){              
                Decimal totalAmount = 0;
                Decimal UpdatedtotalAmount = 0;
                
                // calculate sum Totaal_Merlijn__c of Declaratie__c records     
                for(Declaratie__c DeclaratieRecord : dossierRecord.Declaraties__r){    
                    totalAmount = totalAmount + DeclaratieRecord.Totaal_Merlijn__c;
                }
 system.debug(totalAmount);               
                
                

                if(totalAmount != 0){                   
                    // Find Inkoop_Uren__c record having maximun Betaald_max__c  
                    Partij__c partijMaxBetaaldValue = dossierRecord.Partijen__r[0];
                    for(Partij__c partijRecord : dossierRecord.Partijen__r){                                          
                        if(   partijRecord.Betaald_max__c != null && partijMaxBetaaldValue.Betaald_max__c !=null
                           && partijRecord.Betaald_max__c >= partijMaxBetaaldValue.Betaald_max__c){                              
                            partijMaxBetaaldValue.Betaald_max__c = partijRecord.Betaald_max__c;
                        }                                           
                    }
                    
                    // Find Partij__c record having maximun Betaald_max__c create Facturatie__c 
                    if( partijMaxBetaaldValue != null){
                        Facturatie__c  facturatieRecord;
                        if(totalAmount <= partijMaxBetaaldValue.Betaald_max__c){
                            facturatieRecord = CreateInvoice(partijMaxBetaaldValue ,dossierRecord,totalAmount);
                            UpdatedtotalAmount =0;
                        }else{
                            facturatieRecord = CreateInvoice(partijMaxBetaaldValue ,dossierRecord,partijMaxBetaaldValue.Betaald_max__c);
                            UpdatedtotalAmount = totalAmount - partijMaxBetaaldValue.Betaald_max__c;
                        }
                        if(facturatieRecord != null){
                            facturatieList.add(facturatieRecord);
                        } 
                    }
                    
                    // For reaming record create Facturatie__c on basis of having maximun Betaald__c  
                    for(Partij__c partijRecord : dossierRecord.Partijen__r){                  
                        if(    partijMaxBetaaldValue != partijRecord && UpdatedtotalAmount != 0 
                            && partijRecord.Betaald__c != null && partijRecord.Betaald_max__c != null && UpdatedtotalAmount >= 0){
                            Double invoiceAmount =(totalAmount*(partijRecord.Betaald__c/100));
                            UpdatedtotalAmount = UpdatedtotalAmount - invoiceAmount;
                            
                            Facturatie__c  facturatieRecord = CreateInvoice(partijRecord,dossierRecord,invoiceAmount );                            
                            if(facturatieRecord != null){
                                facturatieList.add(facturatieRecord);
                            }                            
                        }
                    }
                }       
            }
            
            // insert newly created Facturatie__c records 
            if(!facturatieList.IsEmpty()){
system.debug('line 19'); 
                try { 
system.debug('line 20');  
                   database.insert(facturatieList,false);
                   System.debug('facturatieList'+facturatieList);
                }catch(Exception e ){
system.debug('line 21'); 
                     System.debug('The following exception has occurred' + e.getMessage() );
                } 
            }
        } 
    }
   
    // Create invoice records
    public Facturatie__c  CreateInvoice(Partij__c partijRecord,Dossier__c dossierRecord,Decimal invoiceAmount){
system.debug('line 22');        
        if(partijRecord != null && dossierRecord != null && invoiceAmount != null ){
system.debug('line 23');                       
            Facturatie__c facturatieRecord = new Facturatie__c();
            facturatieRecord.Dossier__c = dossierRecord.Id;
            facturatieRecord.Factuur_Datum__c = System.today();
            facturatieRecord.Verval_datum__c =  System.today().addDays(30);
            facturatieRecord.Factuur_Bedrag__c = invoiceAmount; 
            facturatieRecord.Contactpersoon__c = partijRecord.Partij__c;    
            facturatieRecord.Account__c = partijRecord.Partij__r.AccountId;   
                      
            return facturatieRecord;                                 
        } 
        return null;           
    }
    
    public void finish(Database.BatchableContext BC){
system.debug('line 24');        
    }
     
}
 
@isTest
public class BatchDossierInvoiceTestClass{
    @testSetup
    // Creating Test Data
    public static  void testData(){

        Account account = new Account(Name = 'TestAccount1');
        insert account;

        List<Dossier__c> dossierList = new List<Dossier__c>();
        for(integer counter=0;counter<200;counter++){

            Dossier__c dossierRecord = new Dossier__c();
            dossierRecord.Name = 'TestRecord'+counter;
            dossierRecord.Status__c = 'Klant';
            dossierRecord.Partijen__c = 'een team';
            dossierRecord.Datum_eerste_gesprek__c = System.today();
            dossierList.add(dossierRecord);
        }
        insert dossierList;

        List<Partij__c> partijList = new List<Partij__c>();
        for(integer counter=0;counter<200;counter++){
            Partij__c partijRecord = new Partij__c();
            partijRecord.Dossier__c = dossierList[counter].Id;
            partijRecord.Betaald_max__c = 100;
            partijRecord.Betaald__c = 10;
            partijList.add(partijRecord);
        }
        insert partijList;

        List<Partij__c> partijList2 = new List<Partij__c>();
        for(integer counter=0;counter<200;counter++){
            Partij__c partijRecord = new Partij__c();
            partijRecord.Dossier__c = dossierList[counter].Id;
            partijRecord.Betaald_max__c = 0;
            partijRecord.Betaald__c = 10;
            partijList2.add(partijRecord);
        }
        insert partijList2;

        List<Declaratie__c> DeclaratieList = new List<Declaratie__c>();
        for(integer counter=0;counter<200;counter++){
            Declaratie__c DeclaratieRecord = new Declaratie__c();
            DeclaratieRecord.Dossier__c =  dossierList[counter].Id;
            //DeclaratieRecord.Totaal_Merlijn__c = Totaal_Reisuren_Merlijn_new__c + Totaal_Reiskosten_Melijn_new__c + Totaal_Uren_Merlijn__c;
            DeclaratieList.add(DeclaratieRecord);
        }
        insert DeclaratieList;

    }@istest

    public static void  testschedule() {

        Test.StartTest();
        System.schedule('Scheduled Job 2', '0 0 * * * ?', new BatchDossierInvoice ());
        dateTime dt=System.now().addMinutes(1);
        String Csec,Cmin,Chr,Cday,Cmonth,CYear;
        Csec=String.valueof(dt.second());
        Cmin=String.valueof(dt.minute());
        Chr=String.valueof(dt.hour());
        Cday=String.valueof(dt.day());
        Cmonth=String.valueof(dt.month());
        CYear=String.valueof(dt.Year());
        String SchTimer=Csec+' '+Cmin+' '+Chr+' '+Cday+' '+Cmonth+' ? '+CYear;
        system.debug('*************SchTimer:'+SchTimer);
        BatchDossierInvoice  cas = new BatchDossierInvoice  ();
        system.schedule('Scheduler02: Running at', SchTimer, cas);
        Test.stopTest();
    }
}

 
Could someone help me write a test class for this:
 
private final Facturatie__c a;

    public attachPDF(ApexPages.StandardController standardPageController) {
        a = (Facturatie__c)standardPageController.getRecord(); 
      
    }    
    Facturatie__c  currentRecord = [SELECT id, Accountname__r.Name FROM Facturatie__c WHERE id = :ApexPages.currentPage().getParameters().get('id')];

    public PageReference attachPDF() {

        PageReference pdfPage = Page.Factuur2PDF;
        pdfPage.getParameters().put('id',a.id);
          
        Blob pdfBlob = pdfPage.getContent(); 
        
        Attachment attach = new Attachment(parentId = a.id, Name = 'Factuur ' + '-' + currentRecord.Accountname__r.Name +'-'+ date.today().format() +'.pdf', body = pdfBlob); 
        insert attach;
        
        PageReference pageWhereWeWantToGo = new ApexPages.StandardController(a).view(); 
        pageWhereWeWantToGo.setRedirect(true); 
        return pageWhereWeWantToGo;
    }
}

 
Im a newbie, can someone help me writing a test class for an extended controller PDF attachment see:
 
public with sharing class attachPDF {
private final Facturatie__c a;
    public attachPDF(ApexPages.StandardController standardPageController) {
        a = (Facturatie__c)standardPageController.getRecord();
    }    
    Facturatie__c  currentRecord = [SELECT Id, Accountname__r.Name FROM Facturatie__c WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    
    public PageReference attachPDF() {
        PageReference pdfPage = Page.Factuur2PDF;
        pdfPage.getParameters().put('id',a.id);
        Blob pdfBlob = pdfPage.getContent();
        
        Attachment attach = new Attachment(parentId = a.Id, Name = 'Factuur ' + '-' + currentRecord.Accountname__r.Name +'-'+ date.today().format() +'.pdf', body = pdfBlob); //create the attachment object
        insert attach;
        PageReference pageWhereWeWantToGo = new ApexPages.StandardController(a).view();
        pageWhereWeWantToGo.setRedirect(true);
        return pageWhereWeWantToGo;
    }
}
I have the following controller extetion which works to make a pdf as attachment, but need some help writing a testclass for so far i have the following:
 
public with sharing class attachPDF {
private final Facturatie__c a;
    public attachPDF(ApexPages.StandardController standardPageController) {
        a = (Facturatie__c)standardPageController.getRecord(); //instantiate the Facturatie__c object for the current record  
    }    
    Facturatie__c  currentRecord = [SELECT Id, Accountname__r.Name FROM Facturatie__c WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    
    public PageReference attachPDF() {
        PageReference pdfPage = Page.Factuur2PDF;
        pdfPage.getParameters().put('id',a.id);
        Blob pdfBlob = pdfPage.getContent();
        
        Attachment attach = new Attachment(parentId = a.Id, Name = 'Factuur ' + '-' + currentRecord.Accountname__r.Name +'-'+ date.today().format() +'.pdf', body = pdfBlob); //create the attachment object
        insert attach;
        PageReference pageWhereWeWantToGo = new ApexPages.StandardController(a).view();
        pageWhereWeWantToGo.setRedirect(true);
        return pageWhereWeWantToGo;
    }
}
 
@isTest(seeAllData=true) 
public class attachPDFTestClass {

static testMethod void testAttachments() { 
    Facturatie__c a = new Facturatie__c(Facturatie__c.Accountname__r.Name='Test');
    insert a; 

    Attachment attach=new Attachment(); 
    attach.Name='Unit Test Attachment'; 
    Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body'); 
    attach.body=bodyBlob; attach.parentId=a.id;
    insert attach;

    List<Attachment> attachments=[select id, name from Attachment where parent.id=:a.id]; 
    System.assertEquals(1, attachments.size()); 

    Test.StartTest();
    FeedItem f = new FeedItem();
        f.ParentId = a.id;
        f.body = 'test';
        insert f;
        FeedComment fc = new FeedComment();
        fc.CommentBody = 'legal test';
        fc.FeedItemId = f.Id;
        insert fc;
        Test.StopTest();
        System.assertEquals ('legal test', fc.commentbody); 
    }
}

I get the error invalid field initializer
I get the following error: accounthierarchy  unexpected token: ')'    my code looks like:
List<SObject> results = [SELECT ID FROM Account];
  Set<Id> resultIds = (new Map<Id, SObject>(results)).keySet();  
  Map<Set<Id>,results>  getquick = getHierarchies.getAccountHierarchiesQuick(Set<Id>result);
The class tha i am calling is named:  getHierarchies and looks like:
public static Map<Id,HierarchyNode> getAccountHierarchiesQuick(Set<Id> top_acct_ids) {
    Map<Id,HierarchyNode> nodes = new Map<Id,HierarchyNode>();
    Set<Id> parent_acc_ids = top_acct_ids;
Wat am i doing wrong?
 
I get the following error in my class: Constructor not defined: [HierarchyNode].<Constructor>(Account, HierarchyNode) .

The code looks like:
public class Nodeshierachy {

// Add child nodes
private static void addChildren(List<Account> accs, Map<Id,HierarchyNode> nodes, Set<Id> parent_acc_ids) {
    for (Account acc : accs) {
        HierarchyNode ref_node = nodes.get(acc.ParentId);
        HierarchyNode new_node = new HierarchyNode(acc, ref_node);
        nodes.put(acc.id, new_node);
        if (ref_node != null) {
            ref_node.children.add(new_node);
        }
        if (parent_acc_ids != null) {
            parent_acc_ids.add(acc.id);
        }
    }
}
  for (OfferteLine oli :offerte.OfferteLines.OfferteLine)
I have a unittest which runs fine on Contentversion exept the .adderror is not covered in my trigger. How do i catch expectedExceptionThrown where as with an system debug i get: DEBUG|link.LinkedEntityId ContentDocumentLink:{LinkedEntityId=0013E00000COrXWQA1, Id=06A3E0000000eVkUAI}. Here is my unittest:
@IsTest(seeAllData=false)
private class TestNoteOnContentversion {
	
    @IsTest 
    static void refuse_shouldAddError_whenOrderregelIsLocked() {
        // arrange
        Account acc = new Account(
        	Name = 'TEST_ACCT', 
            Account_Status_DS__c = 'Status'
        );
        insert acc;
        
        Orderregel__c orderregel = new Orderregel__c(
            Account__c = acc.Id,
            Orderbegindatum__c = Date.today()
        );
        
        insert orderregel;
        
    	ContentVersion content=new ContentVersion(); 
        content.Title='Header_Picture1'; 
        content.PathOnClient='/' + content.Title + '.jpg'; 
        Blob bodyBlob=Blob.valueOf('Unit Test ContentVersion Body'); 
        content.VersionData=bodyBlob; 
        content.origin = 'H';
    	insert content;
    	
        ContentDocumentLink link=new ContentDocumentLink();
        link.LinkedEntityId=acc.id;
        link.contentdocumentid=[select contentdocumentid from contentversion where id =: content.id].contentdocumentid;
        link.ShareType = 'V';
       
    	insert link;
		
        //Id parentId = link.LinkedEntityId;
        
        // Query the Orderregels to lock
        Orderregel__c[] ord = [SELECT Id from Orderregel__c WHERE Account__c  = : acc.Id];
        
  		// Lock the accounts
		Approval.LockResult[] lrList = Approval.lock(ord, false);
        
		Test.startTest();
        try { 
              update content;
            }
        catch (Exception dmx) 
        { 
           Boolean expectedExceptionThrown = dmx.getMessage().contains('link.LinkedEntityId,Id') ? true : false; 
           system.debug(expectedExceptionThrown);
            System.assertEquals(expectedExceptionThrown, false);  
        }
        Test.stopTest();
    }   
}

 
@istest
public class TestNoteOnContentDocuments {
  static testmethod void NoteOnContentDoc(){
    ContentVersion contentVersion = new ContentVersion(
      Title = 'Penguins',
      PathOnClient = 'Penguins.jpg',
      VersionData = Blob.valueOf('Test Content'),
      IsMajorVersion = true
    );
    insert contentVersion;  
     

	List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];      
    
        ContentDocumentLink link=new ContentDocumentLink();
            link.LinkedEntityId=ContentDocumentLink.id;
            link.contentdocumentid=[select contentdocumentid from contentversion where id =:                  ContentDocument.id].contentdocumentid;
            link.ShareType = 'A';
   
        insert link;
 
      
     DmlException expectedException;
    Test.startTest();
        try { delete documents; }
        catch (DmlException dmx) { 
            
       Boolean expectedExceptionThrown = dmx.getMessage().contains('Approval pending. You do not have the permission to edit/delete this note/attachment, please contact your administrator.') ? true : false; 
       System.assertEquals(expectedExceptionThrown, true);  
        }
    Test.stopTest();
 }
}

 
trigger NoteOnContentDocument on ContentDocument (before delete) {
    for (ContentDocument c : Trigger.old){
        List<ContentDocumentLink> links = [
            SELECT LinkedEntityId 
            FROM ContentDocumentLink 
            WHERE ContentDocumentId= :c.Id
        ];
        if (Approval.isLocked(links.get(1).LinkedEntityId)){
            c.addError('Approval pending. You do not have the permission to delete this note, Please contact your administrator.');
           }    
    }
}

 
How do i write a unittest for the email class. I attached my code below:
public class SendemailController {
public String OpportunityId {get;set;}

Public SendemailController(){
OpportunityId = ApexPages.currentPage().getParameters().get('Id');
}

Public Pagereference sendEmailFunction(){
Opportunity getEmail = [SELECT Id, Contact__r.email FROM Opportunity WHERE id=:OpportunityId];
   if(getEmail.Contact__r.email != null) {
     String toaddress = getEmail.Contact__r.email;

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {toaddress};
String[] ccAddresses = new String[] {toaddress};
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
mail.setReplyTo(toaddress);
mail.setSenderDisplayName('Name');
mail.setSubject('Testing email through apex');
mail.setBccSender(false);
mail.setUseSignature(true);
mail.setPlainTextBody('Dear tester, here are the attechments. This mail is sent trough apex');

List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();        
for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :OpportunityId]){
   Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
   efa.setFileName(a.Name);
   efa.setBody(a.Body);
   fileAttachments.add(efa);
}    

mail.setFileAttachments(fileAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
  PageReference reference = new PageReference('https://eu11.salesforce.com/'+ OpportunityId);
  reference.setRedirect(true);
  return reference;
  }
}
public class CreateInvoice{
    
    public CreateInvoice(){
        
        List<Training__c> trainingList = new List<Training__c>();
        List<Facturatie__c> facturatieList = new List<Facturatie__c>();
        
        try {
        trainingList = [SELECT id , NAME, Startdatum__c,factuur_bedrijf__c,
                          (SELECT Cursist_Prijs__c, Training__c, Cursist__c,CreatedDate,Prijs_training__c,
                           korting__c,Id 
                           FROM Trainingen_Volgen__r ) 
                       FROM  Training__c 
                       WHERE id NOT IN (SELECT  Training__c FROM Facturatie__c)];
        }catch (Exception e) {
            System.debug('The following exception has occurred' + e.getMessage() +
                         'At line number :' + e.getLineNumber() + 'Error' +
                         e.getStackTraceString());
        }              
        if(!trainingList.IsEmpty()){
            
            for(Training__c trainingRecord : trainingList){
                
                if(!trainingRecord.Trainingen_Volgen__r.IsEmpty()){
                    
                    for(Cursist__c cursistRecord : trainingRecord.Trainingen_Volgen__r){
                        
                        Facturatie__c facturatieRecord = checkDate(cursistRecord,trainingRecord);
                        facturatieList.add(facturatieRecord);
                    }
                }   
            }

            if(!facturatieList.IsEmpty()){  
               try {
                   insert facturatieList;
                }catch (Exception e) {
                    System.debug('The following exception has occurred' + e.getMessage() +
                                 'At line number :' + e.getLineNumber() + 'Error' +
                                 e.getStackTraceString());
                }   
               
            }
        }   
    }
    
    public Facturatie__c checkDate(Cursist__c cursistRecord,Training__c trainingRecord){
        
        if(cursistRecord != null && trainingRecord != null){
            Date todaysDate = system.today();
            
            if( todaysDate.addDays(-21) >= trainingRecord.Startdatum__c 
                && todaysDate >= cursistRecord.CreatedDate 
                && todaysDate.addDays(-1) >= trainingRecord.Startdatum__c){
                
                Facturatie__c facturatieRecord = new Facturatie__c();
                
                facturatieRecord.Training__c = trainingRecord.Id;   
                facturatieRecord.Factuur_Datum__c = todaysDate;  
                facturatieRecord.Verval_datum__c = todaysDate.addDays(30);
                
                if(cursistRecord.Prijs_training__c != null &&  cursistRecord.korting__c != null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.Prijs_training__c - cursistRecord.korting__c;
                }else if(cursistRecord.Prijs_training__c != null && cursistRecord.korting__c == null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.Prijs_training__c;
                }else if(cursistRecord.Prijs_training__c == null && cursistRecord.korting__c != null){
                    facturatieRecord.Factuur_Bedrag__c = cursistRecord.korting__c ;
                }
                
                facturatieRecord.Korting__c =  cursistRecord.korting__c;
                facturatieRecord.cursist_prijs__c= cursistRecord.Cursist_Prijs__c ;
                facturatieRecord.Contactpersoon__c = cursistRecord.Cursist__c;
                facturatieRecord.Account__c = trainingRecord.factuur_bedrijf__c; 
                
                return facturatieRecord;
            }
        }
        
        return null;
    }
}
 
@isTest
public class CreateInvoiceTestClass{
    
    // Creating Test Data
   @isTest public static void testData(){
    
        Account account = new Account(Name = 'TestAccount1');  
        insert account;
        
        List<Training__c> trainingList = new List<Training__c>();
        for(integer counter=0;counter<200;counter++){
            
            Training__c trainingRecord = new Training__c();
            trainingRecord.name = 'TestRecord'+counter;
            trainingRecord.Startdatum__c = System.today().addDays(+2);
            trainingRecord.factuur_bedrijf__c = account.Id;
            trainingList.add(trainingRecord);
        }
        insert trainingList;
        
         List<Facturatie__c> facturatieList = new List<Facturatie__c>();
        for(integer counter=0;counter<200;counter++){
            
            Facturatie__c facturatieRecord = new Facturatie__c();
            facturatieRecord.name = 'TestRecord'+counter;
            facturatieRecord.Factuur_Bedrag__c = 1000;
            facturatieRecord.Training__c = trainingList[counter].Id;
            facturatieList.add(facturatieRecord);
        }
        insert facturatieList;

       
        List<Cursist__c> cursistList = new List<Cursist__c>();
        for(integer counter=0;counter<200;counter++){
            
            Cursist__c cursistRecord = new Cursist__c();           
            cursistRecord.Training__c = trainingList[counter].Id;
            cursistRecord.Prijs_training__c = 10;
            cursistRecord.korting__c = 10;
            cursistRecord.CreatedDate = System.today();
            cursistList.add(cursistRecord);
        }
        insert cursistList;
       
       system.debug(facturatieList[0].Account__c);
       Test.StartTEst();
	   CreateInvoice createInv = new CreateInvoice();
	   Test.stopTest();
      
       System.assertEquals(facturatieList[0].Account__c,null);
       
    }
   
}
User-added image
 
public class BatchDossierInvoice implements Database.Batchable<sObject>,Schedulable  {

    public void execute(SchedulableContext SC) {
       Database.executeBatch(new BatchDossierInvoice(), 200); 
    }

    public Database.QueryLocator start(Database.BatchableContext info){
system.debug('line 3');  
     try{
       
                    String query = 'SELECT Id ,(SELECT Id , Betaald_max__c ,Betaald__c,Partij__c,Partij__r.AccountId '+
                                    'FROM Partijen__r ORDER BY Betaald__c DESC ), '+
                                    '(SELECT Id , Dossier__c,Totaal_Merlijn__c '+
                                    'FROM Declaraties__r) '+
                        'FROM Dossier__c '+
                        'WHERE Id IN (SELECT Dossier__c FROM Declaratie__c) '+
                        'AND createddate >= LAST_N_DAYS:30';
         
         
     
         return Database.getQueryLocator(query); 
         system.debug(query);
         
        }catch(Exception e ){
         
            System.debug('The following exception has occurred' + e.getMessage());
        } 
        return null;                    
    }
   
    public void execute(Database.BatchableContext bc, List<Dossier__c> dossierList){     
        
        if(!dossierList.IsEmpty() && dossierList != null){
            List<Facturatie__c> facturatieList = new List<Facturatie__c>();    
            
            for(Dossier__c dossierRecord : dossierList){              
                Decimal totalAmount = 0;
                Decimal UpdatedtotalAmount = 0;
                
                // calculate sum Totaal_Merlijn__c of Declaratie__c records     
                for(Declaratie__c DeclaratieRecord : dossierRecord.Declaraties__r){    
                    totalAmount = totalAmount + DeclaratieRecord.Totaal_Merlijn__c;
                }
 system.debug(totalAmount);               
                
                

                if(totalAmount != 0){                   
                    // Find Inkoop_Uren__c record having maximun Betaald_max__c  
                    Partij__c partijMaxBetaaldValue = dossierRecord.Partijen__r[0];
                    for(Partij__c partijRecord : dossierRecord.Partijen__r){                                          
                        if(   partijRecord.Betaald_max__c != null && partijMaxBetaaldValue.Betaald_max__c !=null
                           && partijRecord.Betaald_max__c >= partijMaxBetaaldValue.Betaald_max__c){                              
                            partijMaxBetaaldValue.Betaald_max__c = partijRecord.Betaald_max__c;
                        }                                           
                    }
                    
                    // Find Partij__c record having maximun Betaald_max__c create Facturatie__c 
                    if( partijMaxBetaaldValue != null){
                        Facturatie__c  facturatieRecord;
                        if(totalAmount <= partijMaxBetaaldValue.Betaald_max__c){
                            facturatieRecord = CreateInvoice(partijMaxBetaaldValue ,dossierRecord,totalAmount);
                            UpdatedtotalAmount =0;
                        }else{
                            facturatieRecord = CreateInvoice(partijMaxBetaaldValue ,dossierRecord,partijMaxBetaaldValue.Betaald_max__c);
                            UpdatedtotalAmount = totalAmount - partijMaxBetaaldValue.Betaald_max__c;
                        }
                        if(facturatieRecord != null){
                            facturatieList.add(facturatieRecord);
                        } 
                    }
                    
                    // For reaming record create Facturatie__c on basis of having maximun Betaald__c  
                    for(Partij__c partijRecord : dossierRecord.Partijen__r){                  
                        if(    partijMaxBetaaldValue != partijRecord && UpdatedtotalAmount != 0 
                            && partijRecord.Betaald__c != null && partijRecord.Betaald_max__c != null && UpdatedtotalAmount >= 0){
                            Double invoiceAmount =(totalAmount*(partijRecord.Betaald__c/100));
                            UpdatedtotalAmount = UpdatedtotalAmount - invoiceAmount;
                            
                            Facturatie__c  facturatieRecord = CreateInvoice(partijRecord,dossierRecord,invoiceAmount );                            
                            if(facturatieRecord != null){
                                facturatieList.add(facturatieRecord);
                            }                            
                        }
                    }
                }       
            }
            
            // insert newly created Facturatie__c records 
            if(!facturatieList.IsEmpty()){
system.debug('line 19'); 
                try { 
system.debug('line 20');  
                   database.insert(facturatieList,false);
                   System.debug('facturatieList'+facturatieList);
                }catch(Exception e ){
system.debug('line 21'); 
                     System.debug('The following exception has occurred' + e.getMessage() );
                } 
            }
        } 
    }
   
    // Create invoice records
    public Facturatie__c  CreateInvoice(Partij__c partijRecord,Dossier__c dossierRecord,Decimal invoiceAmount){
system.debug('line 22');        
        if(partijRecord != null && dossierRecord != null && invoiceAmount != null ){
system.debug('line 23');                       
            Facturatie__c facturatieRecord = new Facturatie__c();
            facturatieRecord.Dossier__c = dossierRecord.Id;
            facturatieRecord.Factuur_Datum__c = System.today();
            facturatieRecord.Verval_datum__c =  System.today().addDays(30);
            facturatieRecord.Factuur_Bedrag__c = invoiceAmount; 
            facturatieRecord.Contactpersoon__c = partijRecord.Partij__c;    
            facturatieRecord.Account__c = partijRecord.Partij__r.AccountId;   
                      
            return facturatieRecord;                                 
        } 
        return null;           
    }
    
    public void finish(Database.BatchableContext BC){
system.debug('line 24');        
    }
     
}
 
@isTest
public class BatchDossierInvoiceTestClass{
    @testSetup
    // Creating Test Data
    public static  void testData(){

        Account account = new Account(Name = 'TestAccount1');
        insert account;

        List<Dossier__c> dossierList = new List<Dossier__c>();
        for(integer counter=0;counter<200;counter++){

            Dossier__c dossierRecord = new Dossier__c();
            dossierRecord.Name = 'TestRecord'+counter;
            dossierRecord.Status__c = 'Klant';
            dossierRecord.Partijen__c = 'een team';
            dossierRecord.Datum_eerste_gesprek__c = System.today();
            dossierList.add(dossierRecord);
        }
        insert dossierList;

        List<Partij__c> partijList = new List<Partij__c>();
        for(integer counter=0;counter<200;counter++){
            Partij__c partijRecord = new Partij__c();
            partijRecord.Dossier__c = dossierList[counter].Id;
            partijRecord.Betaald_max__c = 100;
            partijRecord.Betaald__c = 10;
            partijList.add(partijRecord);
        }
        insert partijList;

        List<Partij__c> partijList2 = new List<Partij__c>();
        for(integer counter=0;counter<200;counter++){
            Partij__c partijRecord = new Partij__c();
            partijRecord.Dossier__c = dossierList[counter].Id;
            partijRecord.Betaald_max__c = 0;
            partijRecord.Betaald__c = 10;
            partijList2.add(partijRecord);
        }
        insert partijList2;

        List<Declaratie__c> DeclaratieList = new List<Declaratie__c>();
        for(integer counter=0;counter<200;counter++){
            Declaratie__c DeclaratieRecord = new Declaratie__c();
            DeclaratieRecord.Dossier__c =  dossierList[counter].Id;
            //DeclaratieRecord.Totaal_Merlijn__c = Totaal_Reisuren_Merlijn_new__c + Totaal_Reiskosten_Melijn_new__c + Totaal_Uren_Merlijn__c;
            DeclaratieList.add(DeclaratieRecord);
        }
        insert DeclaratieList;

    }@istest

    public static void  testschedule() {

        Test.StartTest();
        System.schedule('Scheduled Job 2', '0 0 * * * ?', new BatchDossierInvoice ());
        dateTime dt=System.now().addMinutes(1);
        String Csec,Cmin,Chr,Cday,Cmonth,CYear;
        Csec=String.valueof(dt.second());
        Cmin=String.valueof(dt.minute());
        Chr=String.valueof(dt.hour());
        Cday=String.valueof(dt.day());
        Cmonth=String.valueof(dt.month());
        CYear=String.valueof(dt.Year());
        String SchTimer=Csec+' '+Cmin+' '+Chr+' '+Cday+' '+Cmonth+' ? '+CYear;
        system.debug('*************SchTimer:'+SchTimer);
        BatchDossierInvoice  cas = new BatchDossierInvoice  ();
        system.schedule('Scheduler02: Running at', SchTimer, cas);
        Test.stopTest();
    }
}

 
I have the following controller extetion which works to make a pdf as attachment, but need some help writing a testclass for so far i have the following:
 
public with sharing class attachPDF {
private final Facturatie__c a;
    public attachPDF(ApexPages.StandardController standardPageController) {
        a = (Facturatie__c)standardPageController.getRecord(); //instantiate the Facturatie__c object for the current record  
    }    
    Facturatie__c  currentRecord = [SELECT Id, Accountname__r.Name FROM Facturatie__c WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    
    public PageReference attachPDF() {
        PageReference pdfPage = Page.Factuur2PDF;
        pdfPage.getParameters().put('id',a.id);
        Blob pdfBlob = pdfPage.getContent();
        
        Attachment attach = new Attachment(parentId = a.Id, Name = 'Factuur ' + '-' + currentRecord.Accountname__r.Name +'-'+ date.today().format() +'.pdf', body = pdfBlob); //create the attachment object
        insert attach;
        PageReference pageWhereWeWantToGo = new ApexPages.StandardController(a).view();
        pageWhereWeWantToGo.setRedirect(true);
        return pageWhereWeWantToGo;
    }
}
 
@isTest(seeAllData=true) 
public class attachPDFTestClass {

static testMethod void testAttachments() { 
    Facturatie__c a = new Facturatie__c(Facturatie__c.Accountname__r.Name='Test');
    insert a; 

    Attachment attach=new Attachment(); 
    attach.Name='Unit Test Attachment'; 
    Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body'); 
    attach.body=bodyBlob; attach.parentId=a.id;
    insert attach;

    List<Attachment> attachments=[select id, name from Attachment where parent.id=:a.id]; 
    System.assertEquals(1, attachments.size()); 

    Test.StartTest();
    FeedItem f = new FeedItem();
        f.ParentId = a.id;
        f.body = 'test';
        insert f;
        FeedComment fc = new FeedComment();
        fc.CommentBody = 'legal test';
        fc.FeedItemId = f.Id;
        insert fc;
        Test.StopTest();
        System.assertEquals ('legal test', fc.commentbody); 
    }
}

I get the error invalid field initializer
I have a unittest which runs fine on Contentversion exept the .adderror is not covered in my trigger. How do i catch expectedExceptionThrown where as with an system debug i get: DEBUG|link.LinkedEntityId ContentDocumentLink:{LinkedEntityId=0013E00000COrXWQA1, Id=06A3E0000000eVkUAI}. Here is my unittest:
@IsTest(seeAllData=false)
private class TestNoteOnContentversion {
	
    @IsTest 
    static void refuse_shouldAddError_whenOrderregelIsLocked() {
        // arrange
        Account acc = new Account(
        	Name = 'TEST_ACCT', 
            Account_Status_DS__c = 'Status'
        );
        insert acc;
        
        Orderregel__c orderregel = new Orderregel__c(
            Account__c = acc.Id,
            Orderbegindatum__c = Date.today()
        );
        
        insert orderregel;
        
    	ContentVersion content=new ContentVersion(); 
        content.Title='Header_Picture1'; 
        content.PathOnClient='/' + content.Title + '.jpg'; 
        Blob bodyBlob=Blob.valueOf('Unit Test ContentVersion Body'); 
        content.VersionData=bodyBlob; 
        content.origin = 'H';
    	insert content;
    	
        ContentDocumentLink link=new ContentDocumentLink();
        link.LinkedEntityId=acc.id;
        link.contentdocumentid=[select contentdocumentid from contentversion where id =: content.id].contentdocumentid;
        link.ShareType = 'V';
       
    	insert link;
		
        //Id parentId = link.LinkedEntityId;
        
        // Query the Orderregels to lock
        Orderregel__c[] ord = [SELECT Id from Orderregel__c WHERE Account__c  = : acc.Id];
        
  		// Lock the accounts
		Approval.LockResult[] lrList = Approval.lock(ord, false);
        
		Test.startTest();
        try { 
              update content;
            }
        catch (Exception dmx) 
        { 
           Boolean expectedExceptionThrown = dmx.getMessage().contains('link.LinkedEntityId,Id') ? true : false; 
           system.debug(expectedExceptionThrown);
            System.assertEquals(expectedExceptionThrown, false);  
        }
        Test.stopTest();
    }   
}

 
trigger NoteOnContentDocument on ContentDocument (before delete) {
    for (ContentDocument c : Trigger.old){
        List<ContentDocumentLink> links = [
            SELECT LinkedEntityId 
            FROM ContentDocumentLink 
            WHERE ContentDocumentId= :c.Id
        ];
        if (Approval.isLocked(links.get(1).LinkedEntityId)){
            c.addError('Approval pending. You do not have the permission to delete this note, Please contact your administrator.');
           }    
    }
}

 
trigger NoteOnContentversion on ContentVersion (before insert, before update) {
	for (ContentVersion c : Trigger.new)  {
        
            for (ContentDocumentLink link : [
                SELECT LinkedEntityId 
                FROM ContentDocumentLink
                WHERE ContentDocumentId = :c.ContentDocumentId
            ]){
                Id parentId = link.LinkedEntityId;
                System.debug('link.LinkedEntityId '+ link);
                
                Boolean isOrderRegel = parentId.getSObjectType() == Orderregel__c.SObjectType;
                
                if (isOrderRegel && Approval.isLocked(parentId)){
                  c.addError('Approval pending. You do not have the permission to edit this note, Please contact your administrator.');
                }
            }
        
    }
}
 
@IsTest
private class NoteOnContentversion {
	
    @IsTest static void refuse_shouldAddError_whenOrderregelIsLocked() {
        // arrange
        Account a = new Account(
        	Name = '123', 
            Account_Status_DS__c = 'Strategic'
        );
        insert a;
        
        Orderregel__c orderregel = new Orderregel__c(
            Account__c = a.Id,
            Orderbegindatum__c = Date.today()
        );
        
        insert orderregel;
        Approval.lock(orderregel);
        
        ContentVersion n = new ContentVersion();
       
        insert n;
        
        ContentDocumentLink cl  = new ContentDocumentLink();
        
        insert cl;
               
        // act
        DmlException caughtException;
        try {
            insert cl;
        	insert n;
        } catch(DmlException e) {
            caughtException = e;
        }
        
        // assert
        System.assertNotEquals(null, caughtException);
    }   
}

 
Hi All, Please help!!

I need to create a trigger on a custom object with a related list note, where the create edit delete permission is removerd from the note record when the approval is set to pending. Could you help with an example and point me in the right direction. I have attached an example below to make thing clearer.
User-added image
I have a trigger on ContentDocumentLink object. I have use case to show total number of Files and number of notes attached if the link was between Events and Content (Files/Notes) using Salesforce Content. And, offcourse, similar thing that needs to be done when a content is removed, I implemented beforeDelete event as well.

Code
trigger ContentDocumentLinkTrg on ContentDocumentLink (after insert, before delete)  
{
    //Check if customization is not enable through custom settings
    if(!CustomSettingsUtil.IsCustomizationEnabled())
    {
        return;
    }
    String BeforeOrAfter = (Trigger.isBefore ? 'Before' : 'After');
    String TriggerType = ''
        + (Trigger.isDelete ? 'Delete' : '')
        + (Trigger.isInsert ? 'Insert' : '');
    system.debug(BeforeOrAfter + ' ' + TriggerType );
    // run TriggerHandler
    new ContentDocumentLinkTriggerHandler().run();
}
Checking the debug log, it is entering the AfterInsert event but not BeforeDelete. I see no restrictions in the SF documentation, can anyone put some light on this, please.