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
raman123raman123 

how can i write test class for below code

trigger populate on project__c (before insert , before update){
 
    
    
     MAP<ID , user> mapCon = new MAP<ID , user>([Select id ,name,city
                                                 from user 
]);
     for(project__c  obj : trigger.new)
       {
        if(obj.delivery_location__c == null)
          {
           user u  = mapcon.get(obj.ownerid);
              if (u.city != null)
              
             obj.Delivery_location__c=u.city;
              else {
                   obj.Delivery_location__c = 'NA';
              }
          }
       
       }
       
       }
Best Answer chosen by raman123
Abdul KhatriAbdul Khatri
Hi Yash,

Sorry but first I would like to optimise your code by below code. The reason your code

Starts directly with the SOQL with no where clause or LIMIT which is never efficient. Always make your trigger to focus on the relevant information. This way your code will work in long term. Please also find the test class with 100% converage.
 
trigger populate on Project__c (before insert , before update) {

    Set<Id> idOwnerSet = new Set<Id>();
	List<Project__c> projectList = new List<Project__c>(); 
    for(project__c obj : trigger.new)
    {
        if(obj.delivery_location__c == null) {
            
            idOwnerSet.add(obj.OwnerId);
            projectList.add(obj);
        }
       
    }    
    
    if(projectList.isEmpty()) return;
    
    Map<Id, User> userMap = new Map<Id, User>([SELECT Id, City FROM User WHERE Id = :idOwnerSet]);
    
    if(userMap.isEmpty()) return;
    
    for(Project__c proj : projectList)
    {
        proj.Delivery_location__c = 'NA';
        if(userMap.get(proj.OwnerId).City != null)
        {
            proj.Delivery_location__c = userMap.get(proj.OwnerId).City;
        }
    }
      
}

 
@isTest
public class populate_Test {
    
    static testMethod void test_user_with_blank_city(){
        
        Id profileId = [SELECT Id FROM Profile WHERE Name = 'Standard User'].Id;
        
        User newUser = new User();
        newUser.FirstName = 'TestUser';
        newUser.LastName = 'testUserLName';
        newUser.Alias = 'tAlias';
        newUser.Email = 'projtestuser1@test.com';
        newUser.Username = 'projtestuser1@test.com';
        newUser.IsActive = true;
        newUser.LanguageLocaleKey = 'en_US';
        newUser.LocaleSidKey = 'en_US';
        newUser.Alias = newUser.FirstName.substring(0,1) + newUser.LastName.substring(0,4);
        newUser.EmailEncodingKey = 'UTF-8';
        newUser.TimeZoneSidKey = 'GMT';
        newUser.ProfileId = profileId;
        Insert newUser; 
        
        Project__c proj = new Project__c();
        proj.OwnerId = newUser.Id;
        insert proj;
        
        Project__c projAfterInsert = [SELECT Id, Delivery_location__c FROM Project__c WHERE Id = :proj.Id];
        
        system.assert(projAfterInsert.Delivery_location__c == 'NA');
    
        newUser.City = 'San Francisco';
        update newUser;
        
        projAfterInsert.Delivery_location__c = null;
        update projAfterInsert;

        Project__c projAfterUpdate = [SELECT Id, Delivery_location__c FROM Project__c WHERE Id = :proj.Id];
        
        system.assert(projAfterUpdate.Delivery_location__c == 'San Francisco');        
        
    } 
       
  
}

 

All Answers

Raj VakatiRaj Vakati
try this code and add required field to project object
 
@isTest
private class projectTest {

    @isTest static void projectTestMethod() {
	
	 Profile pf= [Select Id from profile where Name='System Administrator']; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        
        
        insert uu;
		
		System.runAs(uu){
	project__c  p = new project__c ();
	p.Name='Test';
	insert p ;
	}
	
       
    }
	@isTest static void projectTestMethod1() {
	
	 Profile pf= [Select Id from profile where Name='System Administrator']; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
						 city='Autsin',
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        
        
        insert uu;
		
		System.runAs(uu){
	project__c  p = new project__c ();
	p.Name='Test';
	insert p ;
	}
	
       
    }
    
}

 
raman123raman123
@raj its not working nor related to my code i jus want to change te delivery location field on project by user city field 
 
Raj VakatiRaj Vakati
Looks like this code is correct .. can u check the test class is running successfully or not ?? And see what error you are getting
raman123raman123
0 percent test its getting  
Abdul KhatriAbdul Khatri
Hi Yash,

Sorry but first I would like to optimise your code by below code. The reason your code

Starts directly with the SOQL with no where clause or LIMIT which is never efficient. Always make your trigger to focus on the relevant information. This way your code will work in long term. Please also find the test class with 100% converage.
 
trigger populate on Project__c (before insert , before update) {

    Set<Id> idOwnerSet = new Set<Id>();
	List<Project__c> projectList = new List<Project__c>(); 
    for(project__c obj : trigger.new)
    {
        if(obj.delivery_location__c == null) {
            
            idOwnerSet.add(obj.OwnerId);
            projectList.add(obj);
        }
       
    }    
    
    if(projectList.isEmpty()) return;
    
    Map<Id, User> userMap = new Map<Id, User>([SELECT Id, City FROM User WHERE Id = :idOwnerSet]);
    
    if(userMap.isEmpty()) return;
    
    for(Project__c proj : projectList)
    {
        proj.Delivery_location__c = 'NA';
        if(userMap.get(proj.OwnerId).City != null)
        {
            proj.Delivery_location__c = userMap.get(proj.OwnerId).City;
        }
    }
      
}

 
@isTest
public class populate_Test {
    
    static testMethod void test_user_with_blank_city(){
        
        Id profileId = [SELECT Id FROM Profile WHERE Name = 'Standard User'].Id;
        
        User newUser = new User();
        newUser.FirstName = 'TestUser';
        newUser.LastName = 'testUserLName';
        newUser.Alias = 'tAlias';
        newUser.Email = 'projtestuser1@test.com';
        newUser.Username = 'projtestuser1@test.com';
        newUser.IsActive = true;
        newUser.LanguageLocaleKey = 'en_US';
        newUser.LocaleSidKey = 'en_US';
        newUser.Alias = newUser.FirstName.substring(0,1) + newUser.LastName.substring(0,4);
        newUser.EmailEncodingKey = 'UTF-8';
        newUser.TimeZoneSidKey = 'GMT';
        newUser.ProfileId = profileId;
        Insert newUser; 
        
        Project__c proj = new Project__c();
        proj.OwnerId = newUser.Id;
        insert proj;
        
        Project__c projAfterInsert = [SELECT Id, Delivery_location__c FROM Project__c WHERE Id = :proj.Id];
        
        system.assert(projAfterInsert.Delivery_location__c == 'NA');
    
        newUser.City = 'San Francisco';
        update newUser;
        
        projAfterInsert.Delivery_location__c = null;
        update projAfterInsert;

        Project__c projAfterUpdate = [SELECT Id, Delivery_location__c FROM Project__c WHERE Id = :proj.Id];
        
        system.assert(projAfterUpdate.Delivery_location__c == 'San Francisco');        
        
    } 
       
  
}

 
This was selected as the best answer
RahulRahul
@isTest
Public class ProjectTest {

   static testMethod void MTest() {
    project__c  proj= new project__c();
        proj.name = 'Test';
        proj.delivery_location__c= '';
        insert objAccount;

//User u = [select id,name ,city from user];
}

 
RahulRahul
Try this and Please Mark it as solved if it satisfies your Requirement. I have tested it in my ORG, i got around 87% code coverage