• salesforce_hoonigan
  • NEWBIE
  • 70 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 21
    Questions
  • 25
    Replies
Hi Experts, 

I need some assistance with my apex class. Certain lines are not covered. I am only getting 72% on code coverage:

APEX CLASS:
public class LeadViewRestriction {

    public LeadViewRestriction(ApexPages.StandardController controller) {
        this.controller = controller;
    }

    public PageReference getRedir() {
        Lead l = [Select id, OwnerId From Lead Where Id =: ApexPages.currentPage().getParameters().get('id')];
        User u = [Select Id, Profile.Name from User where Id =: UserInfo.getUserId()];

        PageReference newPage;

        if (u.Profile.Name == 'VL - Sales Agent' && l.OwnerId != u.Id) {
            newPage = Page.LeadBasicView;
        } else {
            return null;
        }


        newPage.getParameters().put('id', l.Id);
        return newPage.setRedirect(true);

    }

    private final ApexPages.StandardController controller;

}
 
@isTest
private class TestLeadViewRestriction {
    @isTest static void testsLeadView() {
        Lead l = new Lead();
        l.Company = 'Test';
        l.LastName = 'Doe';
        l.Lead_Status_NEW__c = 'New';
        insert l;

        Test.startTest();
        PageReference newPage = Page.LeadBasicView;
        Test.setCurrentPage(newPage);
        Test.setCurrentPageReference(newPage);
        newPage.getParameters().put('id',l.id);
        
        ApexPages.StandardController sc = new ApexPages.standardController(l);
        LeadViewRestriction controller = new LeadViewRestriction (sc);
        controller.getRedir();

    }
}

These lines are not covered:
 
Line 14 of Apex Class: newPage = Page.LeadBasicView;
Line 20: newPage.getParameters().put('id', l.Id);
Line 21: return newPage.setRedirect(true);


 
Hi Experts,

I am somewhat apex newb, I need a second eye with my test class and codes. As I am only getting 72% code coverage and I am not sure if I wrote it correctly.

Goal: Redirect the page layout to VF (Displaying 4 fields only) IF the Lead Owner is not equal to Current Running User

VF 1: 
<apex:page standardController="Lead" extensions="LeadViewRestriction" 
    action="{!nullValue(redir.url, urlFor($Action.Lead.View, Lead.id, null, true))}">
</apex:page>

VF 2:
<apex:page standardController="Lead"> 
    <apex:sectionheader title="{!$ObjectType.Lead.label} Detail" subtitle="{!Lead.Company}"/>
        <apex:pageblock mode="maindetail" title="{!$ObjectType.Lead.label} Detail">
            <apex:pageBlockSection title="Lead Information" columns="1"> 
                <apex:outputField title="Lead Owner" value="{!Lead.OwnerId}"/> 
                <apex:outputField title="Company Name" value="{!Lead.Company}"/> 
                <apex:outputField title="Status" value="{!Lead.Lead_Status_NEW__c}"/> <BR></BR>
            </apex:pageBlockSection> 
        </apex:pageBlock> 
</apex:page>

Controller:
public class LeadViewRestriction {

    public LeadViewRestriction (ApexPages.StandardController controller) {
        this.controller = controller;
    }

    public PageReference getRedir() {
        Lead l = [Select id, OwnerId From Lead Where Id =: ApexPages.currentPage().getParameters().get('id')];
        User u = [Select Id, Profile.Name from User where Id =: UserInfo.getUserId()];
        
        PageReference newPage;

        if (u.Profile.Name == 'VL - Sales Agent' && l.OwnerId != u.Id) {
            newPage = Page.LeadBasicView;
        } else {
            return null;
        }


        newPage.getParameters().put('id', l.Id);
        return newPage.setRedirect(true);

    }

    private final ApexPages.StandardController controller;

}

TEST CLASS:
 
@isTest
private class TestLeadViewRestriction {
@isTest static void testsLeadView(){
    Lead l = new Lead();
    l.Company= 'Test';
    l.LastName = 'Doe';
    l.Lead_Status_NEW__c = 'New';
    insert l;

    Test.setCurrentPageReference(new PageReference('Page.LeadBasicView'));
    System.currentPageReference().getParameters().put('Id', l.Id);

    ApexPages.StandardController sc = new ApexPages.standardController(l);
    LeadViewRestriction controller = new LeadViewRestriction (sc);       

    controller.getRedir();


}
}

Any assistance with arranging the framework is greatly appreciated.

Thank you.

 
Hi Experts, 

I am pretty newb with VF. I need some assistance with codes. How can I prevent the users (non-record owners) to see all details in the record. Ie. If the running user is not the owner of the record, he/she should only see the Company Name and Owner field on Leads.

Thank you.
Hi,

I am currently building an Task Counter and I was able to achieve this by counting the Activity History and Open Activity using the current code. My new requirement is to count the number of Activities whether an Activity is a Call or an Email, I will base the criteria by Task Type (ex. Emai, Call - Connected, Call - Not Connected). So basically, I will have a total of 4 fields. 
1. Completed Activities - Call, 
2. Open Activities - Call, 
3. Completed Activities - Email, 
4. Open Activities - Email

I hope you could assist me on modifying my code please.

APEX CLASS
public class ActivityUtils {
     
    //config
     
    String fieldToUpdate = 'Completed_Activities__c'; //this field must be added to each object we're updating
    String fieldOpenToUpdate = 'Open_Activities__c'; //this field must be added to each object we're updating
     
    //state
    set<id> leadIds;
    set<id> provIds;
     
    public ActivityUtils(sObject[] records) {
        leadIds = new set<id>();
        provIds = new set<id>();
        captureWhatAndWhoIds(records);
    }
     
    public void updateLeadActivityCount() {
        if(leadIds.size() == 0) return;
        updateActivityCount('Lead','WhoId', getStringFromIdSet(leadIds));
                updateActivityHistory('Lead','WhoId', getStringFromIdSet(leadIds));
 
    }
    public void updateProvisioningActivityCount() {
        if(provIds.size() == 0) return;
        updateActivityCount('Provisioning__c','WhatId', getStringFromIdSet(provIds));
                updateActivityHistory('Provisioning__c','WhatId', getStringFromIdSet(provIds));
 
    }

    private void updateActivityCount(String objToUpdate, String queryFld, String updateIds) {
        string strQuery = 'SELECT Id, (SELECT Id FROM OpenActivities) FROM ' + objToUpdate + ' WHERE Id IN (' + updateIds + ')';
        sObject[] sobjects = new list<sobject>();
        for(sObject so : database.query(strQuery)) {
            OpenActivity[] oActivities = so.getSObjects('OpenActivities');
            Integer openActivityCount = oActivities == null ? 0 : oActivities.size();
            sObject obj = createObject(objToUpdate, so.Id);
            obj.put(fieldOpenToUpdate, openActivityCount);
            sobjects.add(obj);
            system.debug('openActivityCount: ' + openActivityCount);
        }
        update sobjects;
    }
      
    private void updateActivityHistory(String objToUpdate, String queryFld, String updateIds) {
        string strQuery = 'SELECT Id, (SELECT Id FROM ActivityHistories) FROM ' + objToUpdate + ' WHERE Id IN (' + updateIds + ')';       
System.debug(strQuery);
        sObject[] sobjects = new list<sobject>();
        for(sObject so : database.query(strQuery)) {
            ActivityHistory[] oActivities = so.getSObjects('ActivityHistories');
            Integer closedActivityCount = oActivities == null ? 0 : oActivities.size();
            sObject obj = createObject(objToUpdate, so.Id);
            obj.put(fieldToUpdate, closedActivityCount);
            sobjects.add(obj);
            system.debug('ActivityHistoryCount: ' + closedActivityCount);
        }
        update sobjects;
    }
     
    private void captureWhatAndWhoIds(sObject[] objects) {
        for(sObject o : objects) {
            Id whatId = (Id)o.get('WhatId');
            Id whoId = (Id)o.get('WhoId');
            if(whatId != null) {
                String objectName = getObjectNameFromId(whatId);
                if(objectName == 'provisioning') provIds.add(whatId);
            }
            if(whoId != null) {
                String objectName = getObjectNameFromId(whoId);
                if(objectName == 'lead') leadIds.add(whoId);
            }
        }
    }
     
    private String getObjectNameFromId(Id objId) {
        String preFix = String.valueOf(objId).left(3).toLowercase();
        if(prefix == '00q') return 'lead';
        if(prefix == 'a02') return 'provisioning';
        return '';
    }
     
    private String getStringFromIdSet(set<id> idSet) {
        string idString = '';
        for(Id i : idSet) idString+= '\'' + i + '\',';
        return idString == '' ? idString : idString.left(idString.length()-1); //If idString contains some ids we want to ensure we strip out the last comma
    }
     
    //The main part of the method below was taken from //Taken from http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_dml.htm
    //However we've modified this to accept an object id
    private sObject createObject(String typeName, Id objId) {
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
        if (targetType == null) {
            // throw an exception
        }
         
        // Instantiate an sObject with the type passed in as an argument
        //  at run time.
        return targetType.newSObject(objId);
    }
     
}

TRIGGER
 
trigger ActivityCounterTrigger on Task (after insert, after update, after delete, after undelete) {
     
    sObject[] triggerRecords;
    if(!trigger.isDelete) triggerRecords = trigger.new;
    else triggerRecords = trigger.old;
     
    //Update Open Activity Count
    ActivityUtils au = new ActivityUtils(triggerRecords);
    au.updateLeadActivityCount();
    au.updateProvisioningActivityCount();
}

Thanks in advance.
Hi,

I am currently building an Task Counter and I was able to achieve this by counting the Activity History and Open Activity using the current code. My new requirement is to count the number of Activities whether an Activity is a Call or an Email, I will base the criteria by Task Type (ex. Emai, Call - Connected, Call - Not Connected). So basically, I will have a total of 4 fields. 
1. Completed Activities - Call, 
2. Open Activities - Call, 
3. Completed Activities - Email, 
4. Open Activities - Email

I hope you could assist me on modifying my code please.

Class: 
public class ActivityUtils {
     
    //config
     
    String fieldToUpdate = 'Activity_Logs__c'; //this field must be added to each object we're updating
    String fieldOpenToUpdate = 'Open_Activities__c'; //this field must be added to each object we're updating
     
    //state
    set<id> leadIds;
     
    public ActivityUtils(sObject[] records) {
        leadIds = new set<id>();
        captureWhatAndWhoIds(records);
    }
     
    public void updateLeadActivityCount() {
        if(leadIds.size() == 0) return;
        updateActivityCount('Lead','WhoId', getStringFromIdSet(leadIds));
                updateActivityHistory('Lead','WhoId', getStringFromIdSet(leadIds));
 
    }

    private void updateActivityCount(String objToUpdate, String queryFld, String updateIds) {
        string strQuery = 'SELECT Id, (SELECT Id FROM OpenActivities) FROM ' + objToUpdate + ' WHERE Id IN (' + updateIds + ')';
        sObject[] sobjects = new list<sobject>();
        for(sObject so : database.query(strQuery)) {
            OpenActivity[] oActivities = so.getSObjects('OpenActivities');
            Integer openActivityCount = oActivities == null ? 0 : oActivities.size();
            sObject obj = createObject(objToUpdate, so.Id);
            obj.put(fieldOpenToUpdate, openActivityCount);
            sobjects.add(obj);
            system.debug('openActivityCount: ' + openActivityCount);
        }
        update sobjects;
    }
      
    private void updateActivityHistory(String objToUpdate, String queryFld, String updateIds) {
        string strQuery = 'SELECT Id, (SELECT Id FROM ActivityHistories) FROM ' + objToUpdate + ' WHERE Id IN (' + updateIds + ')';       
System.debug(strQuery);
        sObject[] sobjects = new list<sobject>();
        for(sObject so : database.query(strQuery)) {
            ActivityHistory[] oActivities = so.getSObjects('ActivityHistories');
            Integer closedActivityCount = oActivities == null ? 0 : oActivities.size();
            sObject obj = createObject(objToUpdate, so.Id);
            obj.put(fieldToUpdate, closedActivityCount);
            sobjects.add(obj);
            system.debug('ActivityHistoryCount: ' + closedActivityCount);
        }
        update sobjects;
    }
     
    private void captureWhatAndWhoIds(sObject[] objects) {
        for(sObject o : objects) {
            Id whoId = (Id)o.get('WhoId');
            if(whoId != null) {
                String objectName = getObjectNameFromId(whoId);
                if(objectName == 'lead') leadIds.add(whoId);
            }
        }
    }
     
    private String getObjectNameFromId(Id objId) {
        String preFix = String.valueOf(objId).left(3).toLowercase();
        if(prefix == '00q') return 'lead';
        return '';
    }
     
    private String getStringFromIdSet(set<id> idSet) {
        string idString = '';
        for(Id i : idSet) idString+= '\'' + i + '\',';
        return idString == '' ? idString : idString.left(idString.length()-1); //If idString contains some ids we want to ensure we strip out the last comma
    }
     
    //The main part of the method below was taken from //Taken from http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_dml.htm
    //However we've modified this to accept an object id
    private sObject createObject(String typeName, Id objId) {
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
        if (targetType == null) {
            // throw an exception
        }
         
        // Instantiate an sObject with the type passed in as an argument
        //  at run time.
        return targetType.newSObject(objId);
    }
     
}

Trigger:
trigger ActivityCounterTrigger on Task (after insert, after update, after delete, after undelete) {
     
    sObject[] triggerRecords;
    if(!trigger.isDelete) triggerRecords = trigger.new;
    else triggerRecords = trigger.old;
     
    //Update Open Activity Count
    ActivityUtils au = new ActivityUtils(triggerRecords);
    au.updateLeadActivityCount();

}




 
Hi Experts,

I'm still total newb in apex. I hope you could assist me on this.

Criteria:
Uncheck Textbox1__c (Lead - Parent) if Lookup__c (Document__r - child) was changed to blank.

I would appreciate any help coming from the experts.

Thank you.
Hi Experts,

I need your assistance updating TIN_Uploaded__c (Checkbox) on Lead if the Attachment (Notes and Attachment) Name starts with "TIN". This box should be unchecked if the Attachment is deleted. Also I have another box that will do the same behavior SLA_Uploaded__c but I don't know how to nest them in the code. I've tried building the code but I'm getting error "Variable does not exist: attach.Name" in Line 14.
 
trigger TestAttachmentCheck on Attachment (after insert, after update, after delete, after undelete) {
    List <Lead> LeadList = new List<Lead>();
    Set <Id> LeadIds = new Set <Id>();
    
    for(Attachment attach : trigger.New){
         //Check if added attachment is related to Lead or not
         if(attach.ParentId.getSobjectType() == Lead.SobjectType){
              LeadIds.add(attach.ParentId);
         }
    }
    LeadList = [select id, CIN_Uploaded__c from Lead where id in : LeadIds];
   	for(Lead lead : LeadList){    
    	if((string.valueOf(attach.Name)).startswith('.xls')){
            lead.CIN_Uploaded__c  = true;
        }
        else{
            lead.CIN_Uploaded__c = false;
        }
    }
        update LeadList;
}
I would appreciate any help.

Thanks.
 
Hi Experts,

I hope you could assist me creating a code to auto populate a Lookup field based on a Text field. This text field will always contain the ID of a Lead. The custom Object and Lead doesn't have a direct relationship. The text field will be populated manually

Details:
Object: Cloud File (Custom)
Text Field: Text__c (Residing in Cloud File)
Lookup Field: Lead__c

Any assistance is greatly appreciated.
Hi,

I am new to apex and I need assistance creating a class to attend with my trigger call.
 
trigger TargetCompletionTime on Predecessor_Task__c (before insert, before update) {
    BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
    
    for(Predecessor_Task__c pt : trigger.new)
      {
       if((pt.Actual_Start_Date_Time__c!=null) && (pt.Alloted_Hours__c!=null)) 
         {   
            DateTime d1=BusinessHours.add(stdBusinessHours.Id, pt.Actual_Start_Date_Time__c,
            integer.valueOf(pt.Alloted_Hours__c * 60 * 60 * 1000));
            pt.Target_Completion_Date_Time__c=d1;
         }
         
      }
}

 
Hi All,

Please bear with me since I am a complete newbie with Apex. I need assistance building APEX to count the number of Notes (from Notes and Attachments) in Parent object (Custom Object).

I would appreciate if you can share your code.
Hi All,

Please bear with me since I am a complete newbie with Apex. I need assistance building APEX to count the number of Notes (Standard Object) in Parent object (Custom Object).

I would appreciate if you can share your code.
Hi All,

I am a newb on Apex and I am not sure if I built my test class correctly. I am only getting 63% code coverage. Any help is gladly appreciated.

Trigger:  (I am getting red marks on 14,15,18 and 21)
trigger TotalBusinessHrs on Predecessor_Task__c (before insert, before update) {

    BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
    Decimal Diff1;

for (Predecessor_Task__c pt1: trigger.new)
{
   
    DateTime d1 = DateTime.newInstance(1997, 1, 31, 7, 8, 16);
    DateTime d2 = DateTime.newInstance(1997, 1, 31, 7, 8, 16);
    
    if((pt1.Actual_Start_Date_Time__c!=null) && (pt1.Actual_Completion_Date_Time__c!=null)) {
        
    d1=pt1.Actual_Start_Date_Time__c;
    d2=pt1.Actual_Completion_Date_Time__c;
    
    
    Diff1=BusinessHours.diff(stdBusinessHours.id,d1,d2);
    
    
    pt1.Actual_of_Hours_of_Completion__c=(Diff1/(1*60*60*1000));
    
    }
  }
}
Test Class:
 
@isTest
private class testTotalBusinessHrs{

    public static testMethod void BusinessHrs() {
    
    Decimal Diff1;
    
    // Setup test data
    Project_and_Task__c Proj = new Project_and_Task__c (
    Name = 'Test1');
    insert Proj;
    
    Predecessor_Task__c pt = new Predecessor_Task__c (
    Project_and_Task__c=Proj.Id,
    Activity_Name__c='Test123', 
    Actual_Start_Date_Time__c=System.now(), 
    Alloted_Hours__c=2.00);
    insert pt;
    
    System.debug('Inserting PT with valid Actual_of_Hours_of_Completion__c Num value');
    
    BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
    
    Proj = [select Id, Name from Project_and_Task__c where Name= 'Test1'];
   
    pt = [select Id, Activity_Name__c, Actual_Start_Date_Time__c, Alloted_Hours__c, Actual_of_Hours_of_Completion__c from Predecessor_Task__c 
            where Activity_Name__c= 'Test123'];
                        
    System.assert (pt.Alloted_Hours__c != NULL); 
    System.assert (pt.Actual_Start_Date_Time__c!= NULL); 
    System.assertequals(pt.Actual_of_Hours_of_Completion__c, pt.Actual_of_Hours_of_Completion__c);
    }
}


 
Hi All,

Please bear with me since I am a complete newbie with Apex. I currently have a code and I can't get it to work. Need help.

Requirement: Add Number field and Date/Field respecting the Business Hours/Day and decimals in number field

Detail: 
Business Hours: 7:00 AM - 5:00 PM   ---- Total of 10 hrs.
Actual_Time__c (Date/Time) 
Hours__c (Number field with two decimal places)
Target_Date_Time__c (Date/Time) 

Ex. 1
Actual_Time__c + Hours__c = Target_Date_Time__c 
01/10/2015 7:00 AM + 2.00 = 01/10/2015 9:00 AM

Ex. 2 (respecting Business Hours/Day)
Actual_Time__c + Hours__c = Target_Date_Time__c 
01/10/2015 4:00 PM + 2.00 = 02/10/2015 8:00 AM

Ex. 2 (respecting Business Hours/Day with decimal)
Actual_Time__c + Hours__c = Target_Date_Time__c 
01/10/2015 4:30 PM + 2.00 = 02/10/2015 8:30 AM

CODE:
trigger TargetCompletionTime on Predecessor_Task__c (before insert, before update) {
    
    for(Predecessor_Task__c pt : trigger.new)
        {
            BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
            DateTime d1 = pt.Actual_Time__c ;
            
            if((pt.Actual_Time__c !=null) && (pt.Hours__c !=null)) {
            
            pt.Target_Date_Time__c  = d1.addHours(integer.valueOf(pt.Hours__c));
   }
}
}





 
Hi All,

Please bear with me since I am a complete newbie in Apex. I have a requirement that whatever number is entered on a custom number field, it will add to hours of Date/Time Field.

Ex. Date/Time field = 07/10/2015 1:37 AM
      Custom_Number__c = 5
      Answer should be = 07/10/2015 6:37 AM

I would be glad if someone can share their codes. Thank you.
Hi All,

I'm newb on Test Classes. Any assistance is gladly appreciated. I am having errors when trying to Run the Test Class I've created, it is showing 100% code coverage but has an error on Test Class. It is showing "System.DmlException: Update failed. First exception on row 0 with id a1gJ0000001GZsCIAW; first error: TRANSFER_REQUIRES_READ, The new owner must have read permission: []

Apex Class:
 
trigger SyncOwner on Project_and_Task__c (before insert, before update) {

  for(Project_and_Task__c pt:Trigger.new)                    // For each record
    if(Trigger.isInsert)                                     // If we're inserting
      pt.OwnerId = pt.Assigned_To_Owner__c;                  // Assign ownership from Assigned__c
    else                                                     // Otherwise (an update)
      if(pt.OwnerId != Trigger.oldMap.get(pt.id).OwnerId)       // If ownership has changed
        pt.Assigned_To_Owner__c = pt.OwnerId;                // Place the new owner is assigned
      else                                                   // Otherwise (owner not changed, is an update)
        if(pt.Assigned_To_Owner__c != Trigger.oldMap.get(pt.id).Assigned_To_Owner__c)     // If the Assigned__c field changed
          pt.OwnerId = pt.Assigned_To_Owner__c;             // Assigned ownership from Assigned__c
}
Test Class
@isTest
private class TestSyncOwner {
  static testMethod void test() {
    List<User> testUsers = [select id from user where isactive = true limit 2];
        
    List<Project_and_Task__c> pt= new List<Project_and_Task__c>();
    pt.add(new Project_and_Task__c(Name='test',Assigned_To_Owner__c=testUsers[0].Id));
    pt.add(new Project_and_Task__c(Name='test',Assigned_To_Owner__c=testUsers[1].Id));
    insert pt;

    Map<Id, Project_and_Task__c> refMap = new Map<Id, Project_and_Task__c>([SELECT Id, Assigned_To_Owner__c, OwnerId FROM Project_and_Task__c WHERE Id IN :pt]);

    system.assertEquals(refMap.get(pt[0].Id).OwnerId,testUsers[0].Id); // OwnerId should equal Assigned_To_Owner__c;
    system.assertEquals(refMap.get(pt[1].Id).OwnerId,testUsers[1].Id); // OwnerId should equal Assigned_To_Owner__c;
    pt[0].OwnerId = testUsers[1].Id;
    pt[1].Assigned_To_Owner__c = testUsers[0].Id;
    update pt;
    
    Map<Id, Project_and_Task__c> refMap2 = new Map<Id, Project_and_Task__c>([SELECT Id, Assigned_To_Owner__c, OwnerId FROM Project_and_Task__c WHERE Id IN :pt]);
    
    system.assertEquals(refMap2.get(pt[0].Id).Assigned_To_Owner__c,testUsers[1].Id); // Assigned_To_Owner__c should equal OwnerId now
    system.assertEquals(refMap2.get(pt[1].Id).OwnerId,testUsers[0].Id); // OwnerId should equal Assigned_To_Owner__c now
  }  
}
I will appreciate any help

 
Hello Experts,

I am an Administrator and has very minimal and basic knowledge with Apex. I am having difficulties deploying the Apex Class and triggers into production. Basically, what I wanted to do is to count the number of Activity Records created by a specific User Profile and attached to a Lead and then populate the custom field on Leads called Activity_Count__c. When I test the code on Sandbox, it is working as intended, but when I try to deploy it in Production, I'm getting two errors and need assistance on fixing that.

Here are the errors:

► TaskUpdateLead, Details: Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required
► TestLeadActivityCount.testCountTask(), Details: System.QueryException: List has more than 1 row for assignment to SObject Class.TestLeadActivityCount.testCountTask: line 16, column 1

Below are the codes:

CLASS:
public with sharing class LeadActivityCount {
 
    public static Boolean didRun = false;
    public static String ledsPrefix =  Lead.sObjectType.getDescribe().getKeyPrefix();
 
    /*
    * Takes a set of lead IDs, queries those leads, and updates the activity count if appropriate
    */
    public static void updateLeadCounts(Set<ID> ledsIds) {
 
        if (didRun == false) { //We only want this operation to run once per transaction.
            didRun = true;
 
            //Query all the leads, including the tasks child relationships
            List<Lead> leds = [SELECT ID, Activity_Count__c, (SELECT ID FROM Tasks where CreatedBy.ProfileId='00ed0000000TZr6'), (SELECT ID FROM Events where CreatedBy.ProfileId='00ed0000000TZr6') FROM Lead WHERE ID IN :ledsIds];
            List<Lead> updateLeds = new List<Lead>();
 
            for (Lead l : leds) {
                Integer count = l.tasks.size() + l.events.size();
 
                if (l.Activity_Count__c != count) {
                    l.Activity_Count__c = count;
                    updateLeds.add(l); //we're only doing updates to leads that have changed...no need to modify the others
                }
            }
 
            //Update the appropriate leads
            try {
                update updateLeds;
            } catch (Exception e) {
                //This is controversial. Anything could happen when updating the opportunity..validation rule, security, etc. The key is we don't
                //want the event update to fail...so we put a try catch around the opp update to make sure we don't stop that from happening.
            }
        }
    }
}

TEST CLASS:
@IsTest
private class TestLeadActivityCount {

  public static Boolean didRun = false;
  public static String ledsPrefix =  Lead.sObjectType.getDescribe().getKeyPrefix();
   
    /*
    * Test method for this class and TaskUpdateLead and EventUpdateLead
    */
    public static testMethod void testCountTask() {
        //Setup

        Lead leds = new Lead(lastname='Test', email='1@2.com', company='Test');
        insert leds;

        User u = [select ProfileId from User where ProfileId ='00ed0000000TZr6'];
    
    System.runAs(u) {
        //Insert our first task
        Task t = new Task(subject='Test Activity', whoId = leds.id);
        insert t;
        
        //Verify count
        leds = [SELECT ID, Activity_Count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.Activity_Count__c);

        //Disconnect task from the lead
        didRun = false; //Reset
        t.whoId = null;
        update t;
        //Verify count = 0
        leds = [SELECT ID, Activity_Count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(0,leds.Activity_Count__c);

        didRun = false; //Reset
        //Add an event
        Event e = new Event(subject='Test Event', whoId = leds.id, startDateTime = System.Now(), endDateTime = System.now());
        insert e;

        //Verify count = 1
        leds = [SELECT ID, Activity_Count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.Activity_Count__c);

        //Relink the task to the lead
        didRun = false; //Reset
        t.whoId = leds.id;
        update t;

        //Verify count = 2
        leds = [SELECT ID, Activity_Count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(2,leds.Activity_Count__c);

        //Disconnect the event from the lead
        didRun = false; //Reset
        e.whoId = null;
        update e;

        //Verify count is back down to 1
        leds = [SELECT ID, Activity_Count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(1,leds.Activity_Count__c);

        //Delete the task
        didRun = false; //reset
        delete t;
        //Verify count is back down to 0
        leds = [SELECT ID, Activity_Count__c FROM Lead WHERE ID = :leds.id];
        System.assertEquals(0,leds.Activity_Count__c);
    }
   }
}

TRIGGER:
 
trigger TaskUpdateLead on Task (after delete, after insert, after undelete, after update) {

    Set<ID> ledsIds = new Set<ID>();
    //We only care about tasks linked to leads.
    String prefix =  LeadActivityCount.ledsPrefix;

    //Add any lead ids coming from the new data
    if (Trigger.new != null) {
        for (Task t : Trigger.new) {
            if (t.WhoId != null && String.valueOf(t.whoId).startsWith(prefix) ) {
                ledsIds.add(t.whoId);
            }
        }
    }

    //Also add any lead ids coming from the old data (deletes, moving an activity from one lead to another)
    if (Trigger.old != null) {
        for (Task t : Trigger.old) {
            if (t.WhoId != null && String.valueOf(t.whoId).startsWith(prefix) ) {
                ledsIds.add(t.whoId);
            }
        }
    }

    if (ledsIds.size() > 0)
        LeadActivityCount.updateLeadCounts(ledsIds);

}

Any assistance is greatly appreciated.

 
Hi All,

Please bear with me. I am an APEX newbie and needed some assistance please.

Goal: I wanted to update the checkbox (SentForApproval__c) in Child Object (Rate_sheet__c) to TRUE if the Parent Record (Lead) Status (Lead_Status_NEW__c) was set to "CA Completed". This is a lookup relationship.

Parent Object: Lead
Child Object: Rate_sheet__c

Here's what I have so far and I am unsure how to complete the code or even correct this:
 
trigger CAforApproval on Lead (after update){

	set<Id> leadIds = new set<Id>();
    	map<Id, Lead> mapLead = new map<Id, Lead>();
    	list<Rate_sheet__c> listRateSheet = new list<Rate_sheet__c>();
    
    	for(Lead lead : trigger.new) {
        	leadIds.add(lead.Id);
        	mapLead.put(lead.Id, lead);
        }
    
   	 listRateSheet = [SELECT SentForApproval__c,  Lead__r.Id  FROM Rate_sheet__c WHERE Lead__r.Id  IN : leadIds];
    
    if(listRateSheet.size() > 0) { 
        for(Rate_sheet__c rs : listRateSheet) {

Any help is greatly appreciated. Thank you
Hello,

I am new to APEX and I created a trigger on Attachments. My goal is to set the Attachment to Private for a specific object and the file ends with .xls. It works perfectly fine but I am having creating test class for it and I can't deploy it to production. The code is below, can someone help me build a test class for it?
 
trigger SetAttachmentPrivate on Attachment (before insert) {
    string s;
    for(Attachment record:Trigger.new) {
        if((String.valueOf(record.parentId)).startswith('001') && (String.valueOf(record.Name)).endswith('.xls'))
            record.IsPrivate = TRUE;
    }
}

Any assistance is greatly appreciated. Thanks
Hi Experts,

My test class is failing and I can't figure out why. Any assistance is greatly appreciated.

This is the error message:

System.QueryException: List has no rows for assignment to SObject

Stack Trace Class.GenerateJobOfferController.<init>: line 6, column 1
                   Class.GenerateJobOfferController_Tests.myUnitTest: line 15, column 1

This is the test class as a whole:
 
@isTest
private class GenerateJobOfferController_Tests {

    static Account objAccount;   
    static Contact objContact;
    static Job_Order__c objJobOrder;
    static Candidate__c objCandidate;
    static Candidate_Applications__c objApplication;
    
   
    static testMethod void myUnitTest() {
        // TO DO: implement unit test
         LoadData();
        ApexPages.StandardController stdController = new ApexPages.StandardController(objApplication);
        GenerateJobOfferController objGenerateJobOfferController = new GenerateJobOfferController(stdController);
       
   }
   
   static void LoadData(){
        createAccount();
        createContact();
        createJobOrder();
        createCandidate();
        createApplication();
        
   }
   
   static void createAccount(){
        objAccount = new Account();
        objAccount.Name = 'Test Account';
        
        insert objAccount;
        
        //assert..........
        Account TempAccount = new Account();
        TempAccount = [select id from Account where id =:objAccount.id];
        system.assertEquals(TempAccount.id == objAccount.id, true);
    }
    static void createContact(){
        objContact = new Contact();
        objContact.LastName = 'Test Contact';
        objContact.email = 'benX585@gmail.com';
        objContact.AccountId = objAccount.id;
        
        insert objContact;
        
        //assert..........
        Contact TempContact = new Contact();
        TempContact = [select id from Contact where id =:objContact.id];
        system.assertEquals(TempContact.id == objContact.id, true);
    }
    
    static void createJobOrder(){
        objJobOrder = new Job_Order__c();
        objJobOrder.Job_Title__c = 'Test Title';
        objJobOrder.Start_Date__c = date.today();
        objJobOrder.End_Date__c = date.today();
        objJobOrder.Status__c = 'Hiring';
        objJobOrder.Contact_Client__c = objContact.id;
        objJobOrder.Salary_Range__c = '123-123';
        objJobOrder.Experience_level_desired__c = 'Student';
        
        insert objJobOrder;
        
        //assert..........
        Job_Order__c TempJobOrder = new Job_Order__c();
        TempJobOrder = [select id from Job_Order__c where id =:objJobOrder.id];
        system.assertEquals(TempJobOrder.id == objJobOrder.id, true);
    }
    static void createCandidate(){
        objCandidate = new Candidate__c();
        objCandidate.Last_Name__c = 'Test Candidate';
                
        insert objCandidate;
        
        //assert..........
        Candidate__c TempCandidate = new Candidate__c();
        TempCandidate = [select id from Candidate__c where id =:objCandidate.id];
        system.assertEquals(TempCandidate.id == objCandidate.id, true);
    }
        
   static void createApplication(){
        objApplication = new Candidate_Applications__c();
        objApplication.Candidate_Status__c = 'New';
        objApplication.Job_Order__c = objJobOrder.id;
        objApplication.Candidate__c = objCandidate.id;
        
        insert objApplication;
        
        //assert..........
        Candidate_Applications__c TempApplication = new Candidate_Applications__c();
        TempApplication = [select id from Candidate_Applications__c where id =:objApplication.id];
        system.assertEquals(TempApplication.id == objApplication.id, true);
    }
    
  }

Thank you in advance.
Hi All,

Please bear with me. I only have very basic knowledge in APEX and I'm just reading around. I need assistance creating a button that will generate PDF form on Contact and should contain Contact details. The output would be:

1. Click Generate Job Offer button.
2. There should be a PDF format details.
3. Job Offer should be attached to Notes and Attachment section.

I've tried to use this link from GitHub and it works perfectly fine but my problem is I don't know how to modify this code that will merge the fields in Contact Record. Any assistance is greatly appreciated on how to call the values from Contacts.
https://gist.github.com/rdehler/53ca87d727970af661b8#file-sample-save-and-open-pdf-button

Thanks in advance.
 
Hi Experts,

I am somewhat apex newb, I need a second eye with my test class and codes. As I am only getting 72% code coverage and I am not sure if I wrote it correctly.

Goal: Redirect the page layout to VF (Displaying 4 fields only) IF the Lead Owner is not equal to Current Running User

VF 1: 
<apex:page standardController="Lead" extensions="LeadViewRestriction" 
    action="{!nullValue(redir.url, urlFor($Action.Lead.View, Lead.id, null, true))}">
</apex:page>

VF 2:
<apex:page standardController="Lead"> 
    <apex:sectionheader title="{!$ObjectType.Lead.label} Detail" subtitle="{!Lead.Company}"/>
        <apex:pageblock mode="maindetail" title="{!$ObjectType.Lead.label} Detail">
            <apex:pageBlockSection title="Lead Information" columns="1"> 
                <apex:outputField title="Lead Owner" value="{!Lead.OwnerId}"/> 
                <apex:outputField title="Company Name" value="{!Lead.Company}"/> 
                <apex:outputField title="Status" value="{!Lead.Lead_Status_NEW__c}"/> <BR></BR>
            </apex:pageBlockSection> 
        </apex:pageBlock> 
</apex:page>

Controller:
public class LeadViewRestriction {

    public LeadViewRestriction (ApexPages.StandardController controller) {
        this.controller = controller;
    }

    public PageReference getRedir() {
        Lead l = [Select id, OwnerId From Lead Where Id =: ApexPages.currentPage().getParameters().get('id')];
        User u = [Select Id, Profile.Name from User where Id =: UserInfo.getUserId()];
        
        PageReference newPage;

        if (u.Profile.Name == 'VL - Sales Agent' && l.OwnerId != u.Id) {
            newPage = Page.LeadBasicView;
        } else {
            return null;
        }


        newPage.getParameters().put('id', l.Id);
        return newPage.setRedirect(true);

    }

    private final ApexPages.StandardController controller;

}

TEST CLASS:
 
@isTest
private class TestLeadViewRestriction {
@isTest static void testsLeadView(){
    Lead l = new Lead();
    l.Company= 'Test';
    l.LastName = 'Doe';
    l.Lead_Status_NEW__c = 'New';
    insert l;

    Test.setCurrentPageReference(new PageReference('Page.LeadBasicView'));
    System.currentPageReference().getParameters().put('Id', l.Id);

    ApexPages.StandardController sc = new ApexPages.standardController(l);
    LeadViewRestriction controller = new LeadViewRestriction (sc);       

    controller.getRedir();


}
}

Any assistance with arranging the framework is greatly appreciated.

Thank you.

 
Hi,

I am currently building an Task Counter and I was able to achieve this by counting the Activity History and Open Activity using the current code. My new requirement is to count the number of Activities whether an Activity is a Call or an Email, I will base the criteria by Task Type (ex. Emai, Call - Connected, Call - Not Connected). So basically, I will have a total of 4 fields. 
1. Completed Activities - Call, 
2. Open Activities - Call, 
3. Completed Activities - Email, 
4. Open Activities - Email

I hope you could assist me on modifying my code please.

Class: 
public class ActivityUtils {
     
    //config
     
    String fieldToUpdate = 'Activity_Logs__c'; //this field must be added to each object we're updating
    String fieldOpenToUpdate = 'Open_Activities__c'; //this field must be added to each object we're updating
     
    //state
    set<id> leadIds;
     
    public ActivityUtils(sObject[] records) {
        leadIds = new set<id>();
        captureWhatAndWhoIds(records);
    }
     
    public void updateLeadActivityCount() {
        if(leadIds.size() == 0) return;
        updateActivityCount('Lead','WhoId', getStringFromIdSet(leadIds));
                updateActivityHistory('Lead','WhoId', getStringFromIdSet(leadIds));
 
    }

    private void updateActivityCount(String objToUpdate, String queryFld, String updateIds) {
        string strQuery = 'SELECT Id, (SELECT Id FROM OpenActivities) FROM ' + objToUpdate + ' WHERE Id IN (' + updateIds + ')';
        sObject[] sobjects = new list<sobject>();
        for(sObject so : database.query(strQuery)) {
            OpenActivity[] oActivities = so.getSObjects('OpenActivities');
            Integer openActivityCount = oActivities == null ? 0 : oActivities.size();
            sObject obj = createObject(objToUpdate, so.Id);
            obj.put(fieldOpenToUpdate, openActivityCount);
            sobjects.add(obj);
            system.debug('openActivityCount: ' + openActivityCount);
        }
        update sobjects;
    }
      
    private void updateActivityHistory(String objToUpdate, String queryFld, String updateIds) {
        string strQuery = 'SELECT Id, (SELECT Id FROM ActivityHistories) FROM ' + objToUpdate + ' WHERE Id IN (' + updateIds + ')';       
System.debug(strQuery);
        sObject[] sobjects = new list<sobject>();
        for(sObject so : database.query(strQuery)) {
            ActivityHistory[] oActivities = so.getSObjects('ActivityHistories');
            Integer closedActivityCount = oActivities == null ? 0 : oActivities.size();
            sObject obj = createObject(objToUpdate, so.Id);
            obj.put(fieldToUpdate, closedActivityCount);
            sobjects.add(obj);
            system.debug('ActivityHistoryCount: ' + closedActivityCount);
        }
        update sobjects;
    }
     
    private void captureWhatAndWhoIds(sObject[] objects) {
        for(sObject o : objects) {
            Id whoId = (Id)o.get('WhoId');
            if(whoId != null) {
                String objectName = getObjectNameFromId(whoId);
                if(objectName == 'lead') leadIds.add(whoId);
            }
        }
    }
     
    private String getObjectNameFromId(Id objId) {
        String preFix = String.valueOf(objId).left(3).toLowercase();
        if(prefix == '00q') return 'lead';
        return '';
    }
     
    private String getStringFromIdSet(set<id> idSet) {
        string idString = '';
        for(Id i : idSet) idString+= '\'' + i + '\',';
        return idString == '' ? idString : idString.left(idString.length()-1); //If idString contains some ids we want to ensure we strip out the last comma
    }
     
    //The main part of the method below was taken from //Taken from http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_dml.htm
    //However we've modified this to accept an object id
    private sObject createObject(String typeName, Id objId) {
        Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
        if (targetType == null) {
            // throw an exception
        }
         
        // Instantiate an sObject with the type passed in as an argument
        //  at run time.
        return targetType.newSObject(objId);
    }
     
}

Trigger:
trigger ActivityCounterTrigger on Task (after insert, after update, after delete, after undelete) {
     
    sObject[] triggerRecords;
    if(!trigger.isDelete) triggerRecords = trigger.new;
    else triggerRecords = trigger.old;
     
    //Update Open Activity Count
    ActivityUtils au = new ActivityUtils(triggerRecords);
    au.updateLeadActivityCount();

}




 
Hi Experts,

I'm still total newb in apex. I hope you could assist me on this.

Criteria:
Uncheck Textbox1__c (Lead - Parent) if Lookup__c (Document__r - child) was changed to blank.

I would appreciate any help coming from the experts.

Thank you.
Hi Experts,

I need your assistance updating TIN_Uploaded__c (Checkbox) on Lead if the Attachment (Notes and Attachment) Name starts with "TIN". This box should be unchecked if the Attachment is deleted. Also I have another box that will do the same behavior SLA_Uploaded__c but I don't know how to nest them in the code. I've tried building the code but I'm getting error "Variable does not exist: attach.Name" in Line 14.
 
trigger TestAttachmentCheck on Attachment (after insert, after update, after delete, after undelete) {
    List <Lead> LeadList = new List<Lead>();
    Set <Id> LeadIds = new Set <Id>();
    
    for(Attachment attach : trigger.New){
         //Check if added attachment is related to Lead or not
         if(attach.ParentId.getSobjectType() == Lead.SobjectType){
              LeadIds.add(attach.ParentId);
         }
    }
    LeadList = [select id, CIN_Uploaded__c from Lead where id in : LeadIds];
   	for(Lead lead : LeadList){    
    	if((string.valueOf(attach.Name)).startswith('.xls')){
            lead.CIN_Uploaded__c  = true;
        }
        else{
            lead.CIN_Uploaded__c = false;
        }
    }
        update LeadList;
}
I would appreciate any help.

Thanks.
 
Hi Experts,

I hope you could assist me creating a code to auto populate a Lookup field based on a Text field. This text field will always contain the ID of a Lead. The custom Object and Lead doesn't have a direct relationship. The text field will be populated manually

Details:
Object: Cloud File (Custom)
Text Field: Text__c (Residing in Cloud File)
Lookup Field: Lead__c

Any assistance is greatly appreciated.
Hi All,

I am a newb on Apex and I am not sure if I built my test class correctly. I am only getting 63% code coverage. Any help is gladly appreciated.

Trigger:  (I am getting red marks on 14,15,18 and 21)
trigger TotalBusinessHrs on Predecessor_Task__c (before insert, before update) {

    BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
    Decimal Diff1;

for (Predecessor_Task__c pt1: trigger.new)
{
   
    DateTime d1 = DateTime.newInstance(1997, 1, 31, 7, 8, 16);
    DateTime d2 = DateTime.newInstance(1997, 1, 31, 7, 8, 16);
    
    if((pt1.Actual_Start_Date_Time__c!=null) && (pt1.Actual_Completion_Date_Time__c!=null)) {
        
    d1=pt1.Actual_Start_Date_Time__c;
    d2=pt1.Actual_Completion_Date_Time__c;
    
    
    Diff1=BusinessHours.diff(stdBusinessHours.id,d1,d2);
    
    
    pt1.Actual_of_Hours_of_Completion__c=(Diff1/(1*60*60*1000));
    
    }
  }
}
Test Class:
 
@isTest
private class testTotalBusinessHrs{

    public static testMethod void BusinessHrs() {
    
    Decimal Diff1;
    
    // Setup test data
    Project_and_Task__c Proj = new Project_and_Task__c (
    Name = 'Test1');
    insert Proj;
    
    Predecessor_Task__c pt = new Predecessor_Task__c (
    Project_and_Task__c=Proj.Id,
    Activity_Name__c='Test123', 
    Actual_Start_Date_Time__c=System.now(), 
    Alloted_Hours__c=2.00);
    insert pt;
    
    System.debug('Inserting PT with valid Actual_of_Hours_of_Completion__c Num value');
    
    BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
    
    Proj = [select Id, Name from Project_and_Task__c where Name= 'Test1'];
   
    pt = [select Id, Activity_Name__c, Actual_Start_Date_Time__c, Alloted_Hours__c, Actual_of_Hours_of_Completion__c from Predecessor_Task__c 
            where Activity_Name__c= 'Test123'];
                        
    System.assert (pt.Alloted_Hours__c != NULL); 
    System.assert (pt.Actual_Start_Date_Time__c!= NULL); 
    System.assertequals(pt.Actual_of_Hours_of_Completion__c, pt.Actual_of_Hours_of_Completion__c);
    }
}


 
Hi All,

Please bear with me since I am a complete newbie with Apex. I currently have a code and I can't get it to work. Need help.

Requirement: Add Number field and Date/Field respecting the Business Hours/Day and decimals in number field

Detail: 
Business Hours: 7:00 AM - 5:00 PM   ---- Total of 10 hrs.
Actual_Time__c (Date/Time) 
Hours__c (Number field with two decimal places)
Target_Date_Time__c (Date/Time) 

Ex. 1
Actual_Time__c + Hours__c = Target_Date_Time__c 
01/10/2015 7:00 AM + 2.00 = 01/10/2015 9:00 AM

Ex. 2 (respecting Business Hours/Day)
Actual_Time__c + Hours__c = Target_Date_Time__c 
01/10/2015 4:00 PM + 2.00 = 02/10/2015 8:00 AM

Ex. 2 (respecting Business Hours/Day with decimal)
Actual_Time__c + Hours__c = Target_Date_Time__c 
01/10/2015 4:30 PM + 2.00 = 02/10/2015 8:30 AM

CODE:
trigger TargetCompletionTime on Predecessor_Task__c (before insert, before update) {
    
    for(Predecessor_Task__c pt : trigger.new)
        {
            BusinessHours stdBusinessHours = [select id from BusinessHours where Name = 'Default'];
            DateTime d1 = pt.Actual_Time__c ;
            
            if((pt.Actual_Time__c !=null) && (pt.Hours__c !=null)) {
            
            pt.Target_Date_Time__c  = d1.addHours(integer.valueOf(pt.Hours__c));
   }
}
}





 
Hi All,

I'm newb on Test Classes. Any assistance is gladly appreciated. I am having errors when trying to Run the Test Class I've created, it is showing 100% code coverage but has an error on Test Class. It is showing "System.DmlException: Update failed. First exception on row 0 with id a1gJ0000001GZsCIAW; first error: TRANSFER_REQUIRES_READ, The new owner must have read permission: []

Apex Class:
 
trigger SyncOwner on Project_and_Task__c (before insert, before update) {

  for(Project_and_Task__c pt:Trigger.new)                    // For each record
    if(Trigger.isInsert)                                     // If we're inserting
      pt.OwnerId = pt.Assigned_To_Owner__c;                  // Assign ownership from Assigned__c
    else                                                     // Otherwise (an update)
      if(pt.OwnerId != Trigger.oldMap.get(pt.id).OwnerId)       // If ownership has changed
        pt.Assigned_To_Owner__c = pt.OwnerId;                // Place the new owner is assigned
      else                                                   // Otherwise (owner not changed, is an update)
        if(pt.Assigned_To_Owner__c != Trigger.oldMap.get(pt.id).Assigned_To_Owner__c)     // If the Assigned__c field changed
          pt.OwnerId = pt.Assigned_To_Owner__c;             // Assigned ownership from Assigned__c
}
Test Class
@isTest
private class TestSyncOwner {
  static testMethod void test() {
    List<User> testUsers = [select id from user where isactive = true limit 2];
        
    List<Project_and_Task__c> pt= new List<Project_and_Task__c>();
    pt.add(new Project_and_Task__c(Name='test',Assigned_To_Owner__c=testUsers[0].Id));
    pt.add(new Project_and_Task__c(Name='test',Assigned_To_Owner__c=testUsers[1].Id));
    insert pt;

    Map<Id, Project_and_Task__c> refMap = new Map<Id, Project_and_Task__c>([SELECT Id, Assigned_To_Owner__c, OwnerId FROM Project_and_Task__c WHERE Id IN :pt]);

    system.assertEquals(refMap.get(pt[0].Id).OwnerId,testUsers[0].Id); // OwnerId should equal Assigned_To_Owner__c;
    system.assertEquals(refMap.get(pt[1].Id).OwnerId,testUsers[1].Id); // OwnerId should equal Assigned_To_Owner__c;
    pt[0].OwnerId = testUsers[1].Id;
    pt[1].Assigned_To_Owner__c = testUsers[0].Id;
    update pt;
    
    Map<Id, Project_and_Task__c> refMap2 = new Map<Id, Project_and_Task__c>([SELECT Id, Assigned_To_Owner__c, OwnerId FROM Project_and_Task__c WHERE Id IN :pt]);
    
    system.assertEquals(refMap2.get(pt[0].Id).Assigned_To_Owner__c,testUsers[1].Id); // Assigned_To_Owner__c should equal OwnerId now
    system.assertEquals(refMap2.get(pt[1].Id).OwnerId,testUsers[0].Id); // OwnerId should equal Assigned_To_Owner__c now
  }  
}
I will appreciate any help