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
timaatimaa 

Help to understand unit tests

Hi! I have class:
public class DisplayOpportunity{ 
    public PageReference save() {
        return null;
    }


    public List<Opportunity> Elements {get; set;}
	public String oppId {get; set;}
 

public void init() {
		Elements = [SELECT Name, CreatedDate, StageName FROM Opportunity WHERE StageName='Prospecting' or StageName='Closed Won'];   
        
}    
    public void changeStage() {
     Opportunity getElements=[SELECT StageName FROM Opportunity WHERE Id = :oppId]; 
	 
       getElements.StageName;
      if (getElements.StageName == 'Closed Won')
      {
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Closed Won is set already')); 
}   
        Else {
		update getElements;
        }
 		
		init();
        
 

    } 
}

and test class:
@isTest 
public class TestOpportunity {
	public static testMethod void insertNewOpportunity() {
        
  
        //create new opportunity
 Opportunity opp = new Opportunity();
	   opp.Name = 'test Oppo';
       opp.CloseDate = System.today();
       opp.StageName = 'Prospecting';
    insert opp;         
        
        
                //inilizate controller
DisplayOpportunity myOpp = new DisplayOpportunity ();  
ApexPages.currentPage().getParameters().put('oppId',opp.Id);        
                       
      //call method for StageChange
myOpp.changeStage();       
    
    }
    
}

Can you help me to understand part when I should call method and verify it in test class?
Rory HibbertRory Hibbert
Hi Dzmitry,

After calling your method you should re-extract the opportunity from the database and verify that the stagename has been changed correctly, as per your method:
 
//Isolate the test execution context
test.startTest();
//Call the method
myOpp.changeStage();
test.stopTest();

//Retrieve record back from the database
Opportunity updatedElement = [SELECT StageName FROM Opportunity WHERE Id = :oppId];

//Assert the method has functioned
System.assertEquals('Closed Won', updatedElement.StageName);

 
James LoghryJames Loghry
Hi there,

I strongly recommend that you check out the Unit Testing module on Trailhead here: https://developer.salesforce.com/trailhead/module/apex_testing. The module has some hands on training and elaborates on the hows and whys of unit testing your Apex code.

Cheers,
- James