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
St2018St2018 

How to write unit test?

Im having trouble writing unit test for my method. I've gone through apex testing on trailhead but I don't fully  grasp  how to get started. Its still a confusing topic for me.  Below is the method I would like to write unit test for. An example of how I can test my method  or something similar to code would be helpful.   What my  method does is  onclick of custom button  it will check if the fields are blank if it is blank it will display a message to user that the field is required. Im really stuck on how to get started writing a unit test for this. 
 
WebService static String validationsl(String objId){ 
Opportunity OppSubmit =[select id,Final_Space__c,Date_of_Possession__c,Store_Opening_Projected__c,recordtype.name from opportunity where id =:objId];
jsonResult finalResult=new jsonResult();
finalResult.Message = '';
finalResult.status = true;
   try{
               
            if(OppSubmit.recordtype.name=='Permanent'){
                if(OppSubmit.Final_Space__c == null){
                     getJoinText('"Final Space" is required', finalResult);
                }
                if(OppSubmit.Date_of_Possession__c == null){
                    getJoinText('"Date of Possession (Mutually Agreed)." is required', finalResult);
                }
                if(OppSubmit.Store_Opening_Projected__c == null){
                    getJoinText('"Store Opening (Projected)." is required', finalResult);
                } 
            }
			return JSON.serialize(finalResult);
       
     }catch(exception ex){
 			System.debug('An Exception occured submitting deal for approval :'+ex.getTypeName()+'\t:'+ex.getMessage());
            finalResult.Message +='\n'+ ex.getTypeName()+' : '+ex.getMessage();
            return JSON.serialize(finalResult);      
    }
    
}

 
Best Answer chosen by St2018
Abdul KhatriAbdul Khatri
Unit testing is just a blue print of the logic you have implemented in the class. It help you confirm if you logic work as expected or not. For example in your case. You can making different case scenarios in the test class to test the same method for different values.

If you look at the class logic

When the opportunity with recordtype = "Permanent" get inserted or updated you wanted to get the final result based on the following values

Final_Space__c
Date_of_Possession__c
Store_Opening_Projected__c

In the Unit test you just have to build the data accordinlgy and call your method to test, making sure your test data help passing all the lines in the class that you expected it should go through.

Since your method is returning a String, making sure the result you get in the end match what you expected from the class. 

I hope this clarfies

All Answers

Abdul KhatriAbdul Khatri
You didn't provide the class Name where the method resides so just fake the name in the code below you can change. Here is the sample to help you started. It may cover most of your code probably close to 75%. You can add negative for the exception handling.

System.assetEquals is sometimes not important, you can still live without it but that is not a best practise and also without that you can't guarantee your code work as expected even though it pass without it. So I will always recommend.
 
@isTest
public class testclassName {

    static testMethod void test_validatesl(){
        
		Id recordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Permanent').getRecordTypeId();        
        
        Opportunity opp = new Opportunity (Name = 'Test Opportunity', CloseDate = date.today(), StageName = 'Prospecting', RecordTypeId = recordTypeId);
        insert opp;
        
        String returnValue = <className>.validationsl(opp.Id);
        
        //System.assertEquals(expected, actual) //run assertion to check what you expected is what you got actual
                
    }
    
}

 
Abdul KhatriAbdul Khatri
Was it helpful?
St2018St2018
Abdul thanks but no not quite. I guess I just don't fully understand the concept of unit testing and what exactly I should be testing. Can you write comments next to each line explaining what each line  does?  I tried to  use your example in my code and it didn't work.
Abdul KhatriAbdul Khatri
Unit testing is just a blue print of the logic you have implemented in the class. It help you confirm if you logic work as expected or not. For example in your case. You can making different case scenarios in the test class to test the same method for different values.

If you look at the class logic

When the opportunity with recordtype = "Permanent" get inserted or updated you wanted to get the final result based on the following values

Final_Space__c
Date_of_Possession__c
Store_Opening_Projected__c

In the Unit test you just have to build the data accordinlgy and call your method to test, making sure your test data help passing all the lines in the class that you expected it should go through.

Since your method is returning a String, making sure the result you get in the end match what you expected from the class. 

I hope this clarfies
This was selected as the best answer