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
mounika k 1mounika k 1 

Test Class for Calendar

Hi,

I am trying to write test class for the below class which i am not able to cover , help me on this regartd pls

MY APEX CLASS:
public class testcalendar {
    public string eventsform{set;get;}
    public datetime startdate{set;get;}
    public boolean displayevent{get;set;}
    public time selectedtime {set;get;}
    public String selecteddt {set;get;}
    public string selectdt{set;get;}
    public string stage{set;get;}
    public boolean manualtimeslot {set;get;}
    // public Activity__c activityObj {set;get;}
    public Boolean displaypopup{set;get;} 
    public Boolean displaypopup2{set;get;}
    public Boolean displayPopUp3{set;get;}
    public Boolean displayPopUp4{set;get;}
    public Boolean displayPopUp5{set;get;}
    public blob Attach{set;get;} 
    public Boolean includeMyEvents {get;set;}
    public list<calEvent> events {get;set;}
    
    String dtFormat = 'd MMM yyyy HH:mm:ss z';
    
    public testcalendar()
    {
        // activityObj = new Activity__c();
        includeMyEvents = true;
    } 
    /* public testcalendar(apexpages.StandardController Controller)
{

}*/
    //showing the popup window for create a event
    public void showPopup()
    {       
        displayPopup = true; 
        displaypopup2=true;
    }  
    public PageReference toggleMyEvents() {
        if(includeMyEvents){
            includeMyEvents = false;
        }
        else{
            includeMyEvents = true;
        }
        pageload();
        return null;
    }
    
    /*  public list<event> myevent {set;get;}
public pagereference Editevent()
{

Event v=[select id,StartDateTime,EndDateTime,Start_Date__c,mounika__Event_Status__c from Event where Start_Date__c=:selectdt];
if(v.mounika__Event_Status__c =='Pending')
{
system.debug('v'+v);
myevent.add(v);
pagereference r=new pagereference('/apex/pdfcalendar');
return r;
}
else{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.WARNING,'The cant be Edited anymore as it was confirmed'));
return null;
}

}*/
    public void submit()
    {
        
        string selectmanualtime = string.valueOf(selectedtime);
        string starttime = selectdt+' '+selectmanualtime;
        displaypopup=false;
        
        list<Activity__c> TotalRec = [select Id,stage__c,User__c,Start_Date__c,End_Date__c,Scheduled_Date__c from Activity__c  where Scheduled_Date__c =:selectdt];
        Activity__c activitiy =new Activity__c();
        //for((Activity__c.Start_Date__c) >= system.today())
        
        if(selectdt>=String.valueof(system.today()))
            
        {
            system.debug('selectdt'+selectdt);
            system.debug('Today'+ system.today());
            
            if(TotalRec.size() == 0 )
            {   
                if(stage == 'Pending')
                {
                    activitiy.Start_Date__c = Datetime.valueOf(starttime);
                    activitiy.End_Date__c = activitiy.Start_Date__c;
                    activitiy.stage__c = Stage;  
                    activitiy.mounika__Scheduled_Date__c=selectdt;
                    activitiy.User__c=UserInfo.getUserId();
                    insert activitiy;
                    
                    user u = [select id, name, contactid from user where id =: userinfo.getUserId()];
                    contact c = [select id, name, phone, email from contact where id =: u.ContactId];
                    Event Event =new Event();
                    Event.Subject='Email';
                    Event.Location='Hyderbad';
                    Event.OwnerId=UserInfo.getUserId();
                    Event.WhoId = u.ContactId;
                    Event.mounika__Start_Date__c=activitiy.mounika__Scheduled_Date__c;
                    Event.Event_Status__c= activitiy.stage__c ;
                    Event.StartDateTime=activitiy.Start_Date__c;
                    Event.EndDateTime=activitiy.End_Date__c;
                    system.debug('Event'+Event);
                    insert Event;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Event created succesfully'));
                    Event ee =[select ID,Subject,WhoId,WhatId,OwnerId,StartDateTime,EndDateTime from Event limit 1];
                    StaticResource sr = [Select id,body, name from StaticResource where Name = 'Edoc' limit 1];
                     //Document d=[select id,Name,Body,AuthorId,FolderId,ContentType from document where name ='MyPersonalDocuments'];
                    document document=new document();
                    document.Name=sr.Name;
                    document.Body=sr.Body;
                   // system.debug('Event ID ='+ee.Id);
                    document.AuthorId ='00528000001McCz'; //sr.Id;//UserInfo.getUserId();
                   // document.AuthorId =d.AuthorId;
                   system.debug('document.AuthorId =='+sr.Id);
                    document.FolderId = '00528000001McCz';//UserInfo.getUserId(); // put it in running user's folder
                    //document.FolderId=d.FolderId;
                    system.debug('document.FolderId =='+sr.Id);
                    system.debug('document ='+document);
                    
                    insert document;
                    
                    
                    Attachment at= new attachment();
                    at.Name='event attachment';
                    at.ParentId=Event.id;
                    at.Body=document.body;
                    insert at;
                    
                    /*  List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();       
Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType('testcalendar/pdf');
attach.setFileName('pdfcalendar.pdf');        
blob body = at.Body;       
attach.Body = body;        
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {'mounika.kandala9@gmail.com'});
mail.setSubject('Event Attachment');
//messagebody='<html><body>' +Event.id+ <br></br>   'is </body></html>';
mail.setHtmlBody('Your Event ID:'+Event.id+'<br/>'+
'Start date and Time:'+Event.StartDateTime+'<br/> '+
'End Date and Time:'+Event.EndDateTime+'<br/> '+
'Stage:'+Event.mounika__Event_Status__c+'');
mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });  
mails.add(mail);  
system.debug('mails ='+mails);
if(!mails.isEmpty()) 
{
//	Messaging.SendEmail(mails);
}*/
                    //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Confirm,'Event saved succesfully'));
                    displayPopUp5=true;
                }
                
                else{
                    //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Info,'Please select stage as  pending '));
                    displaypopup3=true;
                }
            }
            else
            {
                //ApexPages.addMessage(new ApexPages.message(ApexPages.severity.WARNING,'Event already exists'));
                displayPopUp4=true;
            }
        }
        
        else{
            displaypopup=false;
            displaypopup2=true;                
        }
        
        
    }
    public PageReference pageLoad() {
        
        events = new list<calEvent>();
        if(includeMyEvents)
        {
            
            for(Event Mypaln1 :[select Id,StartDateTime,EndDateTime, Subject, Location, WhoId, WhatId  from Event where Event_Status__c='Confirmed']){
                datetime startDT = Mypaln1.StartDateTime;            
                datetime endDT = Mypaln1.EndDateTime;
                calEvent MypalnEvent1 =new calEvent();  
                MypalnEvent1.title = 'Event:'+ Mypaln1.subject+ ' ';
                MypalnEvent1.allDay = true;
                MypalnEvent1.startString = startDT;
                MypalnEvent1.endString = endDT;
                MypalnEvent1.url = '/' + Mypaln1.Id;
                MypalnEvent1.className = 'event-Confirmed';
                events.add(MypalnEvent1);
                
            }
            
            for(Event Mypaln2 :[select Id,StartDateTime,EndDateTime, Subject, Location, WhoId, WhatId  from Event where Event_Status__c='pending']){
                datetime startDT = Mypaln2.StartDateTime;            
                datetime endDT = Mypaln2.EndDateTime;
                calEvent MypalnEvent2 =new calEvent();  
                MypalnEvent2.title = 'Event:'+ Mypaln2.subject+ ' ';
                MypalnEvent2.allDay = true;
                MypalnEvent2.startString = startDT;
                MypalnEvent2.endString = endDT;
                MypalnEvent2.url = '/' + Mypaln2.Id;
                MypalnEvent2.className = 'event-Pending';
                events.add(MypalnEvent2);
                
            }
            
        }
        return null;
    }
    
    public void Deleteevent(){
        string selectmanualtime = string.valueOf(selectedtime);
        string starttime = selectdt+' '+selectmanualtime;
        Event e=[select id,StartDateTime,EndDateTime,Start_Date__c from Event where Start_Date__c=:selectdt];
        Activity__c m=[select id,Start_Date__c,mounika__Scheduled_Date__c from Activity__c where mounika__Scheduled_Date__c =:selectdt];
        delete e;
        delete m;
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Confirm,'Event Deleted succesfully'));
    }
    public void UpdateEvent()
    {
        Event e=[select id,StartDateTime,EndDateTime,Start_Date__c,mounika__Event_Status__c from Event where Start_Date__c=:selectdt];
        if(e.mounika__Event_Status__c== 'Pending')
        {
            if(stage == 'Confirmed'){
                e.mounika__Event_Status__c='Confirmed';
                update e;
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Confirm,'Event saved succesfully'));
            }
            else{
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Info,'Please select stage as confirmed to update'));
            }
        }
        else{
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Info,'The stage cant be updated for already completed events'));  
        }
    }
    
    
    
    //Class to hold calendar event data
    public void GetEvents(){
        
    }
    public void cancelevent(){
        displaypopup=false;
        displaypopup2=false; 
        displaypopup3=false;
        displaypopup4=false; 
        displayPopUp5=false;
    }
    public void Rerendertop(){
        displaypopup=true;
        
    }
    public class calEvent{
        public String title {get;set;}
        public Boolean allDay {get;set;}
        public dateTime startString {get;set;}
        public dateTime endString {get;set;}
        public String url {get;set;}
        public String className {get;set;}     
    }
}


Test Class:



@isTest
public class testm {
    
    public static testmethod void test(){
        Id p = [select id from profile where name='Partner Community User'].id;
        
        Account ac = new Account(name ='Grazitti') ;
        insert ac; 
        
        Contact con = new Contact(LastName ='testCon',Email='tester@noemail.com',AccountId = ac.Id);
        insert con;  
        
        User user = new User(alias = 'test123', email='test123@noemail.com',
                             emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                             localesidkey='en_US', profileid = p, country='United States',IsActive =true,
                             ContactId = con.Id,
                             timezonesidkey='America/Los_Angeles', username='tester@noemail.com');
        
        insert user;
        
        system.runAs(user) 
        {
            testcalendar TravelCalendar =new testcalendar(); 
            time t = system.now().time();
            TravelCalendar.selectedtime = t;// Time.newInstance(18, 30, 2, 20);
            TravelCalendar.selecteddt= String.valueof(system.today());//'7/07/2016';
            TravelCalendar.manualtimeslot=true;
            TravelCalendar.Attach=Null;
            TravelCalendar.eventsform='dsf';
            TravelCalendar.selectdt=String.valueof(Datetime.now());
            TravelCalendar.displayevent=true;
            TravelCalendar.startdate=system.now();
            TravelCalendar.displaypopup=true;
            TravelCalendar.displaypopup2=true;   
            TravelCalendar.includeMyEvents=true;
            TravelCalendar.stage='pending';
            TravelCalendar.displaypopup3=true;
            TravelCalendar.displaypopup4=true;
            TravelCalendar.displaypopup5=true;
            TravelCalendar.showPopup();
            TravelCalendar.toggleMyEvents();
            
            TravelCalendar.submit();
            //TravelCalendar.pageLoad();
            
            
            
            activity__c  activitiy1 =new activity__c();
            activitiy1.stage__c='Pending';        
            activitiy1.Start_Date__c= system.today();
            activitiy1.End_Date__c=system.now();
            activitiy1.User__c=user.id;
            insert activitiy1;
            system.debug('act'+activitiy1);
            
            Event e =new Event();
            //e.WhoId=Null;
            e.Event_Status__c='Pending';
            e.OwnerId=User.Id;
            e.StartDateTime=system.today();
            e.EndDateTime= system.now();
            e.Subject='call';
            insert e;
            
            Event OrderUpdate = [SELECT Id, Event_Status__c, StartDateTime FROM Event WHERE Id=:e.Id];
            OrderUpdate.Event_Status__c='Confirmed';
            update OrderUpdate;
            
            Document document;
            
            document = new Document();
            document.Body = Blob.valueOf('Some Text');
            document.IsPublic = true;
            document.Name = 'Edoc';
            document.FolderId = userinfo.getUserId();
            document.AuthorId=userinfo.getUserId();
            insert document;   
            
            Attachment at=new Attachment();
            at.Name='event attachment';
                    at.ParentId=e.id;
                    at.Body=document.body;
                    insert at;
            
           
            TravelCalendar.pageLoad();
            TravelCalendar.Deleteevent();
            TravelCalendar.UpdateEvent();
            TravelCalendar.GetEvents();
            TravelCalendar.cancelevent();
            TravelCalendar.Rerendertop();
           }
    }
}

 
Amit Chaudhary 8Amit Chaudhary 8
Please check below post to learn about test classes
1) http://amitsalesforce.blogspot.com/search/label/Test%20Class
2) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Please try below test class.
@isTest
public class testm 
{
    public static testmethod void test()
	{
        Id p = [select id from profile where name='Partner Community User'].id;

        
        Account ac = new Account(name ='Grazitti') ;
        insert ac; 
        
        Contact con = new Contact(LastName ='testCon',Email='tester@noemail.com',AccountId = ac.Id);
        insert con;  
        
        User user = new User(alias = 'test123', email='test123@noemail.com',
                             emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                             localesidkey='en_US', profileid = p, country='United States',IsActive =true,
                             ContactId = con.Id,
                             timezonesidkey='America/Los_Angeles', username='tester@noemail.com');
        
        insert user;



			
        system.runAs(user) 
        {

			date myDate = date.newInstance(2018, 3, 21);
			String dayString = myDate.format();

			activity__c  activitiy1 =new activity__c();
				activitiy1.stage__c='Pending';        
				activitiy1.Start_Date__c= system.today();
				activitiy1.End_Date__c=system.now();
				activitiy1.User__c=user.id;
				activitiy1.Scheduled_Date__c = myDate ; 
			insert activitiy1;

			testcalendar TravelCalendar =new testcalendar(); 
			TravelCalendar.showPopup();
			TravelCalendar.toggleMyEvents();
			TravelCalendar.cancelevent();
			TravelCalendar.Rerendertop();
			
			
            time t = system.now().time();
            TravelCalendar.selectedtime = t;// Time.newInstance(18, 30, 2, 20);
            TravelCalendar.selecteddt= dayString;
            TravelCalendar.manualtimeslot=true;
            TravelCalendar.Attach=Null;
            TravelCalendar.eventsform='dsf';
			
            TravelCalendar.selectdt = dayString;
            TravelCalendar.displayevent=true;
            TravelCalendar.startdate=system.now();
            TravelCalendar.displaypopup=true;
            TravelCalendar.displaypopup2=true;   
            TravelCalendar.includeMyEvents=true;
            TravelCalendar.stage='Pending';
			
            TravelCalendar.displaypopup3=true;
            TravelCalendar.displaypopup4=true;
            TravelCalendar.displaypopup5=true;
            TravelCalendar.showPopup();
            TravelCalendar.toggleMyEvents();
            
            TravelCalendar.submit();
            
            
            
            Event e =new Event();
            //e.WhoId=Null;
            e.Event_Status__c='Pending';
            e.OwnerId=User.Id;
            e.StartDateTime=system.today();
            e.EndDateTime= system.now();
            e.Subject='call';
            insert e;
            
            Event OrderUpdate = [SELECT Id, Event_Status__c, StartDateTime FROM Event WHERE Id=:e.Id];
            OrderUpdate.Event_Status__c='Confirmed';
            update OrderUpdate;
            
            Document document;
            
            document = new Document();
            document.Body = Blob.valueOf('Some Text');
            document.IsPublic = true;
            document.Name = 'Edoc';
            document.FolderId = userinfo.getUserId();
            document.AuthorId=userinfo.getUserId();
            insert document;   
            
            Attachment at=new Attachment();
            at.Name='event attachment';
                    at.ParentId=e.id;
                    at.Body=document.body;
                    insert at;
            
           
            TravelCalendar.pageLoad();
            TravelCalendar.Deleteevent();
            TravelCalendar.UpdateEvent();
            TravelCalendar.GetEvents();
            TravelCalendar.cancelevent();
            TravelCalendar.Rerendertop();
           }
    }
}



Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

Thanks,
Amit Chaudhary