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
Roman PoltavskiyRoman Poltavskiy 

Test class for attachment like Salesforce Files

Please help me with writing a test for this code!

public with sharing class AttClass {
  
    Id PageId;
    Id contentDocId;
    public Id contentId{get; set;}
    public Blob Body {get;set;}
    public String Name {get;set;}
    id cand;
    public ContentDocument imgExist(Id c){
        try{
            contentDocId = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId =: c LIMIT 1].ContentDocumentId;
            if(contentDocId == null){return null;}
            ContentDocument cdRec = [SELECT Id, LatestPublishedVersionId FROM ContentDocument WHERE Id =: contentDocId];
            System.debug('LatestPublishedVersionId:' + cdRec.LatestPublishedVersionId);
            if(cdRec == null){return null;}
            return cdRec;	
        } catch (Exception e){
            return null;
        }
    } 		
	
    public AttClass() {
		/*cand = [SELECT Id, Name FROM Candidate__c
                WHERE Id = :ApexPages.currentPage().getParameters().get('id')];*/
		//Name = 'Candidate ' + cand.Name + ' Photo';
        cand = ApexPages.currentPage().getParameters().get('id');
		ContentDocument cd = imgExist(cand);
		if(cd != null){
			contentId = cd.LatestPublishedVersionId;
			System.debug('LatestPublVersionId:  ' + contentId);
        }    
    }

    public PageReference save() { 
		if(contentId == null){
			ContentVersion ConVer = createContentVersion(Name, Body);
			contentId = ConVer.Id;
    		 createContentLink(contentId, cand); 
			return null;
        }
        else {
            ApexPages.Message myMsg = new  ApexPages.Message(ApexPages.Severity.ERROR,'You have one photo');
            ApexPages.addMessage(myMsg); 
            return null;
        }
    }    
    

	public static ContentVersion createContentVersion(String Name, Blob Body){
		ContentVersion ConVer = new ContentVersion();
		ConVer.VersionData = Body;
		ConVer.Title = Name;
		ConVer.PathOnClient = Name;

		try {
      		insert ConVer;
      		return ConVer;
    	} catch(DMLException e) {
      		System.debug(e);
      		return null;
    	}
	}

	public static void createContentLink(String contentVersionId, String recordId){

		ContentDocumentLink cdLink = new ContentDocumentLink();
		cdLink.ContentDocumentId = [SELECT ContentDocumentId FROM ContentVersion
									WHERE Id =: contentVersionId].ContentDocumentId;
		cdLink.LinkedEntityId = recordId;
		cdLink.ShareType = 'I';
		cdLink.Visibility = 'AllUsers';

		try{
			insert cdLink;
			
		} catch(DMLException e){
			System.debug(e);
			
		}
	}                    
}
Best Answer chosen by Roman Poltavskiy
Raj VakatiRaj Vakati
Change your VF page name and here is the code with 91 %
 
@isTest 
public class AttClassTest 
{
    static testMethod void testEx1() 
    {
        Account testAccount = new Account();
        testAccount.Name='Test Account' ;
        insert testAccount;
        
        Contact cont = new Contact ();
        cont.FirstName = 'FirstName';
        cont.LastName = 'LastName';
        cont.Email='email@email.com';
        cont.phone='12345678';
        insert cont;
        
        Account acct = new Account(Name='TEST_ACCT');
        insert acct;
        
        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];
        
        //create ContentDocumentLink  record 
        ContentDocumentLink cdl = New ContentDocumentLink();
        cdl.LinkedEntityId = acct.id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.shareType = 'V';
        insert cdl;
        
        System.Test.StartTest(); 
        PageReference pageRef = Page.aaaaaaaaaa; // Add your VF page Name here
        pageRef.getParameters().put('Id', String.valueOf(acct.Id));
        System.Test.setCurrentPage(pageRef);
        AttClass cls = new AttClass();
        cls.Body =Blob.valueOf('Test Content') ; 
        cls.Name='Test' ;
        cls.save();
        AttClass.createContentVersion('Test',Blob.valueOf('Test Content'));
        AttClass.createContentLink(contentVersion.Id , acct.Id);
        cls.contentId =null ;
        cls.save();
        System.Test.StopTest();
    }
    
    
}

 

All Answers

Raj VakatiRaj Vakati
Here is the code
 
@isTest 
public class AttClassTest 
{
    static testMethod void testEx1() 
    {
        Account testAccount = new Account();
        testAccount.Name='Test Account' ;
        insert testAccount;
        
        Contact cont = new Contact ();
        cont.FirstName = 'FirstName';
        cont.LastName = 'LastName';
        cont.Email='email@email.com';
        cont.phone='12345678';
        insert cont;
        
        Account acct = new Account(Name='TEST_ACCT');
        insert acct;
        
        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];
        
        //create ContentDocumentLink  record 
        ContentDocumentLink cdl = New ContentDocumentLink();
        cdl.LinkedEntityId = acct.id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.shareType = 'V';
        insert cdl;
        
        System.Test.StartTest(); 
        PageReference pageRef = Page.aaaaaaaaaa; // Add your VF page Name here
        pageRef.getParameters().put('Id', String.valueOf(acct.Id));
        System.Test.setCurrentPage(pageRef);
        AttClass cls = new AttClass();
        cls.Body =Blob.valueOf('Test Content') ; 
        cls.Name='Test' ;
        cls.save();
        AttClass.createContentVersion('Test',Blob.valueOf('Test Content'));
        AttClass.createContentLink(contentVersion.Id , acct.Id);
        cls.contentId =null ;
        cls.save();
        System.Test.StopTest();
    }
    
    
}

 
Raj VakatiRaj Vakati
Change your VF page name and here is the code with 91 %
 
@isTest 
public class AttClassTest 
{
    static testMethod void testEx1() 
    {
        Account testAccount = new Account();
        testAccount.Name='Test Account' ;
        insert testAccount;
        
        Contact cont = new Contact ();
        cont.FirstName = 'FirstName';
        cont.LastName = 'LastName';
        cont.Email='email@email.com';
        cont.phone='12345678';
        insert cont;
        
        Account acct = new Account(Name='TEST_ACCT');
        insert acct;
        
        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];
        
        //create ContentDocumentLink  record 
        ContentDocumentLink cdl = New ContentDocumentLink();
        cdl.LinkedEntityId = acct.id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.shareType = 'V';
        insert cdl;
        
        System.Test.StartTest(); 
        PageReference pageRef = Page.aaaaaaaaaa; // Add your VF page Name here
        pageRef.getParameters().put('Id', String.valueOf(acct.Id));
        System.Test.setCurrentPage(pageRef);
        AttClass cls = new AttClass();
        cls.Body =Blob.valueOf('Test Content') ; 
        cls.Name='Test' ;
        cls.save();
        AttClass.createContentVersion('Test',Blob.valueOf('Test Content'));
        AttClass.createContentLink(contentVersion.Id , acct.Id);
        cls.contentId =null ;
        cls.save();
        System.Test.StopTest();
    }
    
    
}

 
This was selected as the best answer
Roman PoltavskiyRoman Poltavskiy
Raj Vakati, thank you very much!!! You save my @$$!!!
 
Intigration vIntigration v
Hi Roman/Raj,
I have the similar requirement related to file attachemnts on Lead object,I need to display error when there is already file attached with the same title to that lead record so i have written the class and used that in button to display error message which is working fine.I am facing the issue in writting test class for that code.when i use the above mentioned code ,am getting error like "illegal assignment from list to list "in test class.Here is the line of code in test class where am facing the issue.
 List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
Please tell me what is wrong in that line.also am adding my apex class here.Please help me writing test class for that.

 webservice static Boolean checkDocVersion(id LeadId){
        list<ContentDocumentLink>Doclst= new list<ContentDocumentLink>();
        list<string>verifiedDoc= new list<string>();
        list<Lead> lstLead=new list<Lead>();
        list<string> lstdoctitle=new list<string>();
        Boolean isDocument;
        lstLead=[select Phone,City__c from Lead where id=:LeadId];
        string city='Ver.'+' 0'+lstLead[0].City__c;
        Doclst= [SELECT ContentDocumentId,contentdocument.title FROM ContentDocumentLink WHERE LinkedEntityId =:LeadId];
        
        for(ContentDocumentLink doclink:Doclst){
            if(doclink.contentdocument.title.contains(city)){
                verifiedDoc.add(doclink.contentdocument.title);
            }
            
        }
        if(verifiedDoc.size()>0){
        isDocument=true;
        }
        else{
            isDocument=false;
        }
        return isDocument;
    }

}