+ Start a Discussion
ArmanMArmanM 

Help writing test code for public class

​I have a class that uses email template with Visualforce, this would be used to send emails on opportunity. I have completed this class but I am having trouble writing a test that would pass (>75%). I am using this as reference: 

https://help.salesforce.com/apex/HTViewSolution?id=000181102&language=en_US

This is my apex class: 
public class emailHelper {
    // In a separate class so that it can be used elsewhere
	public Opportunity opp {get;set;}    
	public User myUser { get;set;}

    public emailHelper(ApexPages.StandardController stdController)
    { 
        opp = (opportunity)stdController.getRecord(); 
    }

User currentUser = [Select email from User where username = :UserInfo.getUserName() limit 1];  

    public  PageReference sendEmail() {
    	PageReference emailPage = new PageReference('/email/author/emailauthor.jsp');
        Map<String, String> params = emailPage.getParameters();
            params.put('p3_lkid',opp.ID); //email will be attached to the activity history of the opportunity where the button was clicked using the acct.ID
            params.put('template_id','00X28000000MfO6'); /// template ID of the email template to be shown goes here
            params.put('rtype','003');
            params.put('p24', opp.CS_Resource__c); //Opportunity.CS_Resource__c showing in "Additional to" field
            params.put('p4', opp.Owner.Email);	//cc the opportunity owner
            params.put('p5','email@email.com'); //email address showing in Bcc field
            params.put('new_template','1'); 
            params.put('retURL',ApexPages.currentPage().getUrl()); //after send button is clicked, go back to the opportunity where the button was clicked
             
    return emailPage;
      
    }  
}
Thank you,
Arman
 
Best Answer chosen by ArmanM
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class and let us know if this will help you
@isTest 
private class emailHelperTest {
        static testMethod void testMethod1()        
    {
        Account testAccount = new Account();
            testAccount.Name='Test Account' ;
             // add all required field
        insert testAccount;                         

        // Please update StageName according to your org
        Opportunity oppt = new Opportunity(         
                    Name ='New mAWS Deal',
                    AccountID = testAccount.ID,
                    StageName = 'Negotiations',
                    Amount = 3000,
                    CloseDate = System.today(),
                    Product__c = 'testProduct',
                    CurrencyIsoCode = 'USD',
                    Expected_Amount__c  = 3000,
					Actual_Close_Date__c = system.today(),
                    Targeting_Country__c = 'US'
                    );
                                                    // add all required field
        insert oppt;                               

        Test.StartTest();                           
            ApexPages.StandardController sc = new ApexPages.StandardController(oppt);      
            emailHelper obj = new emailHelper(sc);                                          
            obj.sendEmail();                        
        Test.StopTest();                           
    }
}

 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please check below post to learn about test class
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 sample test class.
@isTest 
public class emailHelperTest 
{
	static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
			testAccount.Name='Test Account' ;
			// add all required field
		insert testAccount;
		
		Opportunity oppt = new Opportunity(Name ='New mAWS Deal',
					AccountID = testAccount.ID,
					StageName = 'Customer Won',
					Amount = 3000,
					CloseDate = System.today()
					);
			// add all required field
		insert oppt;

		Test.StartTest(); 
			ApexPages.StandardController sc = new ApexPages.StandardController(oppt);
			emailHelper obj = new emailHelper(sc);
			obj.sendEmail();

		Test.StopTest();
	}
}

Let us know if this will help you

 
ArmanMArmanM
Hi Amit,

I tried the sample test, but the test was not successful. The following is what I tired: 
@isTest 
private class emailHelperTest {
        static testMethod void testMethod1()        
    {
        Account testAccount = new Account();
            testAccount.Name='Test Account' ;
             // add all required field
        insert testAccount;                         
        
        Opportunity oppt = new Opportunity(         
                    Name ='New mAWS Deal',
                    AccountID = testAccount.ID,
                    StageName = 'Closed Won',
                    Amount = 3000,
                    CloseDate = System.today(),
                    Product__c = 'testProduct',
                    CurrencyIsoCode = 'USD',
                    Expected_Amount__c  = 3000,
                    Targeting_Country__c = 'US'
                    );
                                                    // add all required field
        insert oppt;                               

        Test.StartTest();                           
            ApexPages.StandardController sc = new ApexPages.StandardController(oppt);      
            emailHelper obj = new emailHelper(sc);                                          
            obj.sendEmail();                        
        Test.StopTest();                           
    }
}

Is there something I am doing wrong? How can I modify this test to run successfully with my emailHelper class. I really appreciate any response. 

Thanks,
Arman
Amit Chaudhary 8Amit Chaudhary 8
What error you are geting after executing above test class. ?
ArmanMArmanM
I am getting the following error: 'System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Must fill &quot;Actual Close Date&quot; before setting opportunity as Won: []' 
Amit Chaudhary 8Amit Chaudhary 8
It look like you create some validation rule on opportunity. So you need to to update your code according to same.
Please share that validation rule or try below code.
@isTest 
private class emailHelperTest {
        static testMethod void testMethod1()        
    {
        Account testAccount = new Account();
            testAccount.Name='Test Account' ;
             // add all required field
        insert testAccount;                         

        // Please update StageName according to your org
        Opportunity oppt = new Opportunity(         
                    Name ='New mAWS Deal',
                    AccountID = testAccount.ID,
                    StageName = 'Negotiations',
                    Amount = 3000,
                    CloseDate = System.today(),
                    Product__c = 'testProduct',
                    CurrencyIsoCode = 'USD',
                    Expected_Amount__c  = 3000,
                    Targeting_Country__c = 'US'
                    );
                                                    // add all required field
        insert oppt;                               

        Test.StartTest();                           
            ApexPages.StandardController sc = new ApexPages.StandardController(oppt);      
            emailHelper obj = new emailHelper(sc);                                          
            obj.sendEmail();                        
        Test.StopTest();                           
    }
}

 
ArmanMArmanM
Hi Amit, 

Yes, I do have the following validation rules on opportunity: 

1-
Name: Actual_Close_Date_is_required_for_close
Error Condtion:
​AND ( 
OR ( 
ISPICKVAL(StageName, "Closed Won"), 
ISPICKVAL(StageName, "Closed Won Annual")), 
ISBLANK(Actual_Close_Date__c), 
ISPICKVAL( Department__c, "Brand Solutions") 
)

2- 
Name: Lock_campaign_start_and_end_date
Error Condition: 
AND( 
IsWon = TRUE, 
ISPICKVAL( Department__c, "Brand Solutions"), 
OR( 
ISCHANGED(Campaign_Start_Date__c), 
ISCHANGED(Campaign_End_Date__c)))

3- 
Name: Locked_Expected_Amount_And_Date
Error Condition: 
Probability >= 0.70 
&& (MONTH(CloseDate) = MONTH(TODAY()) + 1) 
&& (DAY(TODAY()) >= 20) 
&& (ISCHANGED(CloseDate) 
|| ISCHANGED(Expected_Amount__c))

4- 
Name: RO_value_required
Error Condition: 
AND ( 
OR ( 
ISPICKVAL(StageName, "Closed Won"), 
ISPICKVAL(StageName, "Closed Won Annual")), 
RO_Value__c = 0.00, 
$Profile.Name = "Standard User" 
)
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class and let us know if this will help you
@isTest 
private class emailHelperTest {
        static testMethod void testMethod1()        
    {
        Account testAccount = new Account();
            testAccount.Name='Test Account' ;
             // add all required field
        insert testAccount;                         

        // Please update StageName according to your org
        Opportunity oppt = new Opportunity(         
                    Name ='New mAWS Deal',
                    AccountID = testAccount.ID,
                    StageName = 'Negotiations',
                    Amount = 3000,
                    CloseDate = System.today(),
                    Product__c = 'testProduct',
                    CurrencyIsoCode = 'USD',
                    Expected_Amount__c  = 3000,
					Actual_Close_Date__c = system.today(),
                    Targeting_Country__c = 'US'
                    );
                                                    // add all required field
        insert oppt;                               

        Test.StartTest();                           
            ApexPages.StandardController sc = new ApexPages.StandardController(oppt);      
            emailHelper obj = new emailHelper(sc);                                          
            obj.sendEmail();                        
        Test.StopTest();                           
    }
}

 
This was selected as the best answer
ArmanMArmanM
Thanks Amit, the test passd but the button and email isn't behaving correctly