• Stephan Spiegel
  • NEWBIE
  • 200 Points
  • Member since 2014

  • Chatter
    Feed
  • 6
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 12
    Replies

I'm trying to prevent multiple SOQL queries in my method by creating a static list outside of the method.
The list is pulling from custom settings, so they should be static when the class runs.
Unfortunately, when I run the test for this class, the debug log shows nothing.
Am I putting this list in the wrong place?

Class
public class modeRanges{

    public static List<ModeRange__c> ModeRanges = [SELECT Mode_Type__c, Spend_Picklist_Value__c, Volume_Picklist_Value__c FROM ModeRange__c];

    public static void setSpendRangeFromVolumeRange(List<Mode__c> Modes){
	System.debug('ModeRanges: ' + ModeRanges);
        for(Mode__c m :Modes){
            for(ModeRange__c r: ModeRanges){
                if(m.Type__c == r.Mode_Type__c && m.Est_Volume__c == r.Volume_Picklist_Value__c){
                    m.Est_Spend__c = r.Spend_Picklist_Value__c;
                }
            }
        }
    }    
}

Debug Log
15:45:01:042 USER_DEBUG [12]|DEBUG|ModeRanges: ()


Trying to find a duplicate lead based on email on a "before insert" trigger. I pushed a SOQL query results into a map. How do I find/compare the duplicates in the Map?
 


trigger LoveMessage on Lead (before insert) {
    List<Lead> newleads = new List<Lead>();
    List<Lead> currentleads = new list<Lead>();
    currentleads = [SELECT Id, Name, Email FROM Lead WHERE Email !=null];
    Map<String, String> compareleads = new Map<String, String>();
   
    for(Lead u: currentleads){
        compareleads.put(u.Name, u.Email);
        System.debug(compareleads);
       
    }
    for(Lead lovelylead:Trigger.new){
        if(lovelylead.Email != null && lovelylead.Email !=compareleads.Email){
            newleads.add(lovelylead);

        }
    }

insert newleads;
}
I have the following trigger  and I am getting this error on the Test Class.  Could someone point out what I am doing wrong on the test class?

API Name
Type
Line
Column
Problem
TestCreateTaskOnInsertWebToLead.TestCreateTaskOnInsertWebToLead() Class 35 1 Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []", Failure Stack Trace: "Class.TestCreateTaskOnInsertWebToLead.TestCreateTaskOnInsertWebToLead: line 35, column 1"

Trigger
User-added image

Class
User-added image
I created the following Apex Class and Apex Trigger. However the code coverage for the Apex Class is only 63% and the Aoex Trigger is 0%.

How do I increase the code coverage for the Apex Class and Apex Trigger?

Apex Class: ApprovedSFDCRequestPDF
Code Coverage: 63% (13/19)
public class ApprovedSFDCRequestPDF
{
    public SFDC__c SFDCReq;
    //public DateTime craDateTime = DateTime.now();
    private ApexPages.StandardController stdController;
    
    public ApprovedSFDCRequestPDF(ApexPages.StandardController stdController)
    {
        this.stdController = stdController;
        SFDCReq = (SFDC__c)stdController.getRecord();
    } 
    // Attach Approved SFDC Request to current SFDC__c 
    
    public PageReference attach()
    {
        DateTime craDateTime = DateTime.now();
        SFDC__c  f=[select id,name,Submitted_for_Approval__c,SFDC_Request_Status__c from SFDC__c where id=:SFDCReq.id];
        if(f.Submitted_for_Approval__c==True&&f.SFDC_Request_Status__c=='Approved')
        {
            // Get the page definition 
            //PageReference pdfPage = Page.ApprovedSFDCRequestPDF;   
            
            PageReference pdfPage = new PageReference('/apex/ApprovedSFDCRequestPDF?id=' + SFDCReq.id);
           
            
            //pdfPage.getParameters().put('id',SFDCReq.id);
             Blob pdfBlob = null;
            // Generate the pdf blob
            if(!Test.isRunningTest())//added by Najma for #00055992
             pdfBlob = pdfPage.getContent();
            else
            pdfBlob = Blob.valueOf('Test');
            //SFDC__c f=[select id,name from SFDC__c where id=:SFDCReq.id];
            // Create the attachment against the Approved SFDC Request page 
            Attachment a = new Attachment(parentId = f.id, name=f.name + ' - SFDC ' + craDateTime.formatlong() + '.pdf', body = pdfBlob);
            // Insert the attachment into the SFDC Request
            
            insert a;
        }
        PageReference p=new PageReference('/'+f.id);
        p.setredirect(true);
        return p;  
    }
}

Apex Trigger:  CreateSFDCRequestTrigger
Code Coverage: 0% (0/3)
trigger CreateSFDCRequestTrigger on SFDC__c (before update) {
     for(SFDC__c  sfdc : trigger.new){
        if(sfdc.FromApprovalProcess__c == true ){
             GenerateCDRPDF.generateCDRPDFAttachment(sfdc.id, 'sfdc', UserInfo.getSessionId());
        }
    }
}

Thanks!

Beth
In my last for loop (last 4-5 lines of code that I post here) I get a cannot de-reference null object error when I try to insert an AHU record into the database.  I've gone over the code a couple of times, and can't figure out what object I don't instantiate. 


trigger updateGatewayCounts on AHU__c (after update, after delete, after insert) {
AHU__c editedAHU = new AHU__c();
if (Trigger.isDelete) {editedAHU = trigger.old[0];}
else {editedAHU = trigger.new[0];}

Map<Control_Gateway__c, Integer[]> cggwCounts = new Map<Control_Gateway__c, Integer[]>();
List<AHU__c> project_AHUs = [SELECT AHU_Project__c, AHU_Site__c, Name, AHU_Control_Group__c
        FROM AHU__c
        WHERE AHU_Project__c = :editedAHU.AHU_Project__c
        ORDER BY Name];
for (AHU__c ahu: project_AHUs) {
  List<AHU_Point__c> points = [SELECT AHU_Point_Source__c, AHU_Point_Type__c, AHU_Point_Gateway__c FROM AHU_Point__c WHERE AHU_Point_AHU__c =: ahu.Id];
  if (points.size() > 0) {
   Map<String, AHU_Point__c[]> sensorMap = new Map<String, AHU_Point__c[]>();
   for (AHU_Point__c point: points) {
    AHU_Point__c[] sensorList = sensorMap.get(point.AHU_Point_Source__c);
    if (sensorList == null) {sensorList = new List<AHU_Point__c>();}
    sensorList.add(point);
    sensorMap.put(point.AHU_Point_Source__c, sensorList);
   }

   for (AHU_Point__c[] hwList: sensorMap.values()) {
    Integer temperature = 0;
    Integer voltage = 0;
    Integer int_temp = 0;
    Integer other = 0;
    String gw = '';
    String source = '';
    for (AHU_Point__c point: hwList) {
     List<Point__c> port = [SELECT Point_Port__c FROM Point__c WHERE Point_Name__c =: point.AHU_Point_Type__c];
     if (port.size() > 0) {
      if (port[0].Point_Port__c == 'Temperature') {temperature += 1;}
      else if (port[0].Point_Port__c == 'Voltage') {voltage += 1;}
      else if (port[0].Point_Port__c == 'Internal Temperature') {int_temp += 1;}
     }
     else {other += 1;}
     gw = point.AHU_Point_Gateway__c;
     source = point.AHU_Point_Source__c;
    }
    List<Control_Gateway__c> cggw = [SELECT CGGW_WAM_Count__c, CGGW_WSM_AHU_Count__c, CGGW_WSM_Power_Count__c
            FROM Control_Gateway__c
            WHERE CGGW_Project__c = :editedAHU.AHU_Project__c AND CGGW_Gateway__c = :gw AND CGGW_Control_Group__c = :ahu.AHU_Control_Group__c];
    Integer[] counts = cggwCounts.get(cggw[0]);
    if (counts == null) {counts = new List<Integer>();counts.add(0);counts.add(0);counts.add(0);}
    if (source == 'WAM') {counts.set(0, counts.get(0)+1);}
    else if (source != 'BACnet') {if (voltage > 0) {counts.set(1, counts.get(1)+1);} else {counts.set(2, counts.get(2)+1);}}
    cggwCounts.put(cggw[0], counts);
   }
  }
}
for (Control_Gateway__c cggw: cggwCounts.keySet()) {
  cggw.CGGW_WAM_Count__c = cggwCounts.get(cggw).get(0);
  cggw.CGGW_WSM_Power_Count__c = cggwCounts.get(cggw).get(1);
  cggw.CGGW_WSM_AHU_Count__c = cggwCounts.get(cggw).get(2);
  upsert(cggw);
}
}
I am totally new at coding apex. I managed to write the code but I have a lot of unanswered questions about how to write the test. Below is the code I need to write the test for and below that is what I have written so far for the test. What is happening in the code is I have a Dedicated Stock (DS) parent object (It contains 8 product manager fields used for an approval process). The DS parent object has a relationship to the SR_Products child objects (0-many). The product child records contain one product manager field and it is filled depending on who the product manager is for the product selected. When an insert or update is done to the SR_Products record the trigger runs to fill in the corresponding product manager field on the parent DS object. The trouble I am having with writing the test is (basically I don't know much here): 1) In the test what happens with formula fields? The child object contains formula fields that are key to the test. Don't know how to fill those. 2)Do you have to put test data in for the parent, child, and user objects. 3) Do I use real Id numbers or how do I set that up? What would I do the assert on? Any help to get me going is appreciated.

trigger SR_Set_Approvers on SR_Products__c (After insert, After Update) {

    // This trigger sets all the product managers from the Stocking Request records
    // With the data from the SR - Product Details records
   
    // Loop all product records that have changed
    for (SR_Products__c prod : Trigger.new) {
       
     system.debug('product name1 = ' + prod.Stocking_Request__c);
        // Get all the product records related to the SR
        SR_Products__c[] allproducts = [SELECT product_manager__c, PM_Type__C,
                                        stocking_request__c
             FROM SR_Products__c
             WHERE stocking_request__c = :Prod.stocking_request__c 
             ];
        String Pm1 = '';
        String Pm2 = '';
        String Pm3 = '';
        String Pm4 = '';
        String Pm5 = '';
        String Pm6 = '';
        String Pm7 = '';
        String Pm8 = '';
   //Set the PM variables with the PM from the SR-Products records       
     for(SR_Products__c p : allproducts) {
       
   If (p.PM_Type__c == 'PM1')
                pm1 = p.product_manager__c;
            If (p.PM_Type__c == 'PM2')
                pm2 = p.product_manager__c;
            If (p.PM_Type__c == 'PM3')
                pm3 = p.product_manager__c;
            If (p.PM_Type__c == 'PM4')
                pm4 = p.product_manager__c;
            If (p.PM_Type__c == 'PM5')
                pm5 = p.product_manager__c;
            If (p.PM_Type__c == 'PM6')
                pm6 = p.product_manager__c;
            If (p.PM_Type__c == 'PM7')
                pm7 = p.product_manager__c;
            If (p.PM_Type__c == 'PM8')
                pm8 = p.product_manager__c;                   
        } //end loop products
       
        // Get the Stocking Request record
        system.debug('product name = ' + prod.Stocking_Request__c);
        Stocking_Request__c sr = [Select ID, Name,
                               Product_Manager_1__c, Product_Manager_2__c,
                               Product_Manager_3__c, Product_Manager_4__c,
                               Product_Manager_5__c, Product_Manager_6__c,
                               Product_Manager_7__c, Product_Manager_8__c
                     From Stocking_Request__c
                     Where ID = :prod.Stocking_Request__c];
       
      // Reset all PM fields to blank to start out with
      sr.Product_Manager_1__c = null;
        sr.Product_Manager_2__c = null;
        sr.Product_Manager_3__c = null;
        sr.Product_Manager_4__c = null;
        sr.Product_Manager_5__c = null;
        sr.Product_Manager_6__c = null;
        sr.Product_Manager_7__c = null;
        sr.Product_Manager_8__c = null;
        // Get the user record IDs for the PM variable fields
        // And set the PM fields in the stocking request record
       system.debug('pm1 ID using =  ' + pm1 + pm2);
        If (PM1 != '' ){
         User u1 = [Select ID, Name
                     From User
                     Where Name = :PM1];           
            If (u1 != null)sr.Product_Manager_1__c = u1.ID;
        } //End PM1 if
       
  system.debug('pm2 ID using =  ' + pm2);
        If (PM2 != '' ){
         User u2 = [Select ID, Name
                     From User
                     Where Name = :PM2];
            If (u2 != null)sr.Product_Manager_2__c = u2.id;
        } //End PM2 if       
  system.debug('pm3 ID using =  ' + pm3);
        If (PM3 != '' ){
         User u3 = [Select ID, Name
                     From User
                     Where Name = :PM3];
            If (u3 != null)sr.Product_Manager_3__c = u3.id;
        } //End PM3 if
        system.debug('pm4 ID using =  ' + pm4);
        If (PM4 != ''){
         User u4 = [Select ID, Name
                     From User
                     Where Name = :PM4];
            If (u4 != null)sr.Product_Manager_4__c = u4.id;
        } //End PM4 if       
        system.debug('pm5 ID using =  ' + pm5);
        If (PM5 != '' ){
         User u5 = [Select ID, Name
                     From User
                     Where Name = :PM5];
            If (u5 != null)sr.Product_Manager_5__c = u5.id;
        } //End PM5 if       
       
        If (PM6 != ''){
         User u6 = [Select ID, Name
                     From User
                     Where Name = :PM6];
            If (u6 != null)sr.Product_Manager_6__c = u6.id;
        } //End PM6 if       
 
        If (PM7 != '' ){
         User u7 = [Select ID, Name
                     From User
                     Where Name = :PM7];
            If (u7 != null)sr.Product_Manager_7__c = u7.id;
        } //End PM7 if       

        If (PM8 != '' ){
         User u8 = [Select ID, Name
                     From User
                     Where Name = :PM8];
            If (u8 != null)sr.Product_Manager_8__c = u8.id;
        } //End PM8 if       
       Update sr;
      
}  // End for looping of changed product records
}


My test so far:

@IsTest

Private class TestSRProducts {
   
    static TestMethod void AddProduct() {
        //Setup new Stocking Request
        Stocking_Request__c AR = new Stocking_Request__c();
        AR.Sold_To__c = 'ABC Company';
        AR.Business_Case__c = 'Bus';
       
       
        //Setup new product
        SR_Products__c testAddP = new SR_Products__c();
        testAddp.Stocking_Request__c = 'ABC Company';
        testAddp.Product__c = '01td00000035nAg';
        testAddp.Form__c = 'Web';
        testAddp.Certification__c = 'FSC';
        testAddp.Pounds__c = 10;
        testAddp.Selling_Price__c = 45.00;
        testAddp.New_or_Existing__c = 'New';
        testAddp.width__c = 12;
        testAddp.Diameter__c = 12;
        testAddp.length__c = 24;
        testaddp.Core_Size__c = 24;
        testaddp.Grain__C = 'Long';
        testaddp.Pounds_Per__c = 'Month';
        Test.startTest();
        insert testaddp;
        Test.stoptest();
       System.assertnotEquals(testaddp.id, null);
      
    } //End AddProduct
       
       
       
} //End Class TestSRProducts

I'm trying to prevent multiple SOQL queries in my method by creating a static list outside of the method.
The list is pulling from custom settings, so they should be static when the class runs.
Unfortunately, when I run the test for this class, the debug log shows nothing.
Am I putting this list in the wrong place?

Class
public class modeRanges{

    public static List<ModeRange__c> ModeRanges = [SELECT Mode_Type__c, Spend_Picklist_Value__c, Volume_Picklist_Value__c FROM ModeRange__c];

    public static void setSpendRangeFromVolumeRange(List<Mode__c> Modes){
	System.debug('ModeRanges: ' + ModeRanges);
        for(Mode__c m :Modes){
            for(ModeRange__c r: ModeRanges){
                if(m.Type__c == r.Mode_Type__c && m.Est_Volume__c == r.Volume_Picklist_Value__c){
                    m.Est_Spend__c = r.Spend_Picklist_Value__c;
                }
            }
        }
    }    
}

Debug Log
15:45:01:042 USER_DEBUG [12]|DEBUG|ModeRanges: ()


Trying to find a duplicate lead based on email on a "before insert" trigger. I pushed a SOQL query results into a map. How do I find/compare the duplicates in the Map?
 


trigger LoveMessage on Lead (before insert) {
    List<Lead> newleads = new List<Lead>();
    List<Lead> currentleads = new list<Lead>();
    currentleads = [SELECT Id, Name, Email FROM Lead WHERE Email !=null];
    Map<String, String> compareleads = new Map<String, String>();
   
    for(Lead u: currentleads){
        compareleads.put(u.Name, u.Email);
        System.debug(compareleads);
       
    }
    for(Lead lovelylead:Trigger.new){
        if(lovelylead.Email != null && lovelylead.Email !=compareleads.Email){
            newleads.add(lovelylead);

        }
    }

insert newleads;
}
Seems to me that the following achomplish the same thing:

List<Account> aa = [SELECT Id, Name FROM Account WHERE Name = 'Acme'];

List<Account> aa = databse.query('SELECT Id, Name FROM Account WHERE Name = 'Acme'');

What are the advantages of using one over the other?
I have the following trigger  and I am getting this error on the Test Class.  Could someone point out what I am doing wrong on the test class?

API Name
Type
Line
Column
Problem
TestCreateTaskOnInsertWebToLead.TestCreateTaskOnInsertWebToLead() Class 35 1 Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []", Failure Stack Trace: "Class.TestCreateTaskOnInsertWebToLead.TestCreateTaskOnInsertWebToLead: line 35, column 1"

Trigger
User-added image

Class
User-added image
I created the following Apex Class and Apex Trigger. However the code coverage for the Apex Class is only 63% and the Aoex Trigger is 0%.

How do I increase the code coverage for the Apex Class and Apex Trigger?

Apex Class: ApprovedSFDCRequestPDF
Code Coverage: 63% (13/19)
public class ApprovedSFDCRequestPDF
{
    public SFDC__c SFDCReq;
    //public DateTime craDateTime = DateTime.now();
    private ApexPages.StandardController stdController;
    
    public ApprovedSFDCRequestPDF(ApexPages.StandardController stdController)
    {
        this.stdController = stdController;
        SFDCReq = (SFDC__c)stdController.getRecord();
    } 
    // Attach Approved SFDC Request to current SFDC__c 
    
    public PageReference attach()
    {
        DateTime craDateTime = DateTime.now();
        SFDC__c  f=[select id,name,Submitted_for_Approval__c,SFDC_Request_Status__c from SFDC__c where id=:SFDCReq.id];
        if(f.Submitted_for_Approval__c==True&&f.SFDC_Request_Status__c=='Approved')
        {
            // Get the page definition 
            //PageReference pdfPage = Page.ApprovedSFDCRequestPDF;   
            
            PageReference pdfPage = new PageReference('/apex/ApprovedSFDCRequestPDF?id=' + SFDCReq.id);
           
            
            //pdfPage.getParameters().put('id',SFDCReq.id);
             Blob pdfBlob = null;
            // Generate the pdf blob
            if(!Test.isRunningTest())//added by Najma for #00055992
             pdfBlob = pdfPage.getContent();
            else
            pdfBlob = Blob.valueOf('Test');
            //SFDC__c f=[select id,name from SFDC__c where id=:SFDCReq.id];
            // Create the attachment against the Approved SFDC Request page 
            Attachment a = new Attachment(parentId = f.id, name=f.name + ' - SFDC ' + craDateTime.formatlong() + '.pdf', body = pdfBlob);
            // Insert the attachment into the SFDC Request
            
            insert a;
        }
        PageReference p=new PageReference('/'+f.id);
        p.setredirect(true);
        return p;  
    }
}

Apex Trigger:  CreateSFDCRequestTrigger
Code Coverage: 0% (0/3)
trigger CreateSFDCRequestTrigger on SFDC__c (before update) {
     for(SFDC__c  sfdc : trigger.new){
        if(sfdc.FromApprovalProcess__c == true ){
             GenerateCDRPDF.generateCDRPDFAttachment(sfdc.id, 'sfdc', UserInfo.getSessionId());
        }
    }
}

Thanks!

Beth
In my last for loop (last 4-5 lines of code that I post here) I get a cannot de-reference null object error when I try to insert an AHU record into the database.  I've gone over the code a couple of times, and can't figure out what object I don't instantiate. 


trigger updateGatewayCounts on AHU__c (after update, after delete, after insert) {
AHU__c editedAHU = new AHU__c();
if (Trigger.isDelete) {editedAHU = trigger.old[0];}
else {editedAHU = trigger.new[0];}

Map<Control_Gateway__c, Integer[]> cggwCounts = new Map<Control_Gateway__c, Integer[]>();
List<AHU__c> project_AHUs = [SELECT AHU_Project__c, AHU_Site__c, Name, AHU_Control_Group__c
        FROM AHU__c
        WHERE AHU_Project__c = :editedAHU.AHU_Project__c
        ORDER BY Name];
for (AHU__c ahu: project_AHUs) {
  List<AHU_Point__c> points = [SELECT AHU_Point_Source__c, AHU_Point_Type__c, AHU_Point_Gateway__c FROM AHU_Point__c WHERE AHU_Point_AHU__c =: ahu.Id];
  if (points.size() > 0) {
   Map<String, AHU_Point__c[]> sensorMap = new Map<String, AHU_Point__c[]>();
   for (AHU_Point__c point: points) {
    AHU_Point__c[] sensorList = sensorMap.get(point.AHU_Point_Source__c);
    if (sensorList == null) {sensorList = new List<AHU_Point__c>();}
    sensorList.add(point);
    sensorMap.put(point.AHU_Point_Source__c, sensorList);
   }

   for (AHU_Point__c[] hwList: sensorMap.values()) {
    Integer temperature = 0;
    Integer voltage = 0;
    Integer int_temp = 0;
    Integer other = 0;
    String gw = '';
    String source = '';
    for (AHU_Point__c point: hwList) {
     List<Point__c> port = [SELECT Point_Port__c FROM Point__c WHERE Point_Name__c =: point.AHU_Point_Type__c];
     if (port.size() > 0) {
      if (port[0].Point_Port__c == 'Temperature') {temperature += 1;}
      else if (port[0].Point_Port__c == 'Voltage') {voltage += 1;}
      else if (port[0].Point_Port__c == 'Internal Temperature') {int_temp += 1;}
     }
     else {other += 1;}
     gw = point.AHU_Point_Gateway__c;
     source = point.AHU_Point_Source__c;
    }
    List<Control_Gateway__c> cggw = [SELECT CGGW_WAM_Count__c, CGGW_WSM_AHU_Count__c, CGGW_WSM_Power_Count__c
            FROM Control_Gateway__c
            WHERE CGGW_Project__c = :editedAHU.AHU_Project__c AND CGGW_Gateway__c = :gw AND CGGW_Control_Group__c = :ahu.AHU_Control_Group__c];
    Integer[] counts = cggwCounts.get(cggw[0]);
    if (counts == null) {counts = new List<Integer>();counts.add(0);counts.add(0);counts.add(0);}
    if (source == 'WAM') {counts.set(0, counts.get(0)+1);}
    else if (source != 'BACnet') {if (voltage > 0) {counts.set(1, counts.get(1)+1);} else {counts.set(2, counts.get(2)+1);}}
    cggwCounts.put(cggw[0], counts);
   }
  }
}
for (Control_Gateway__c cggw: cggwCounts.keySet()) {
  cggw.CGGW_WAM_Count__c = cggwCounts.get(cggw).get(0);
  cggw.CGGW_WSM_Power_Count__c = cggwCounts.get(cggw).get(1);
  cggw.CGGW_WSM_AHU_Count__c = cggwCounts.get(cggw).get(2);
  upsert(cggw);
}
}
Hi all,

I have created a custom visualforce page for forecasting at my company. The page calls a custom controller, which queries the RevenueForecast object for the running user's Quota information.
List<RevenueForecast> quotaList = [select Quota, ProductFamily from RevenueForecast where StartDate =: dateSelected and OwnerId =: userSelected];
This works fine when I log in as a user and open up the visualforce page - the quota values are returned for a selected month as expected.

I also created a test class to test the controller. When I run the test class I receive the following error:

"System.QueryException: sObject type 'RevenueForecast' is not supported."

In the test class I use the SetAllData=true setting and create the user within the code:
@isTest (seeAllData=true)
public class TestForecastView {
	
	@isTest public static void test_method_one() {
		// Tests the view from an end user perspective.
		PageReference pageRef = Page.ForecastView;
        Test.setCurrentPage(pageRef);
        
        //Add test data.
        Profile p = [select id from profile where name='Finance - Sales User'];
        
        User user1 = new User(
            Lastname = 'SuperMan1',
            Alias = 'sprmn1',
            Email = 'super.man1@zywave.com',
            ProfileId = p.Id,
            Username = 'super.man1@zywave.com',
            Who__c = 'BD Rep',
            emailencodingkey='UTF-8',
            languagelocalekey='en_US',
            localesidkey='en_US',
            timezonesidkey='America/Los_Angeles'
        );
        insert user1;
Then towards the end of the test class I call the controller as the new user created above:
//Test the ForecastView Apex page and ForecastViewController Apex controller.
        //================================================================================
        Test.startTest();
        System.runAs(user1){
            ForecastViewController controller = new ForecastViewController();
            controller.Refresh();
            controller.Submit();
            
            ForecastViewController controller1 = new ForecastViewController();
            controller1.Refresh();
            controller1.Submit();
        }
        Test.stopTest();
I don't see any reason why the test is returning an error message. Any assistance you can provide would be much appreciated!

-Kory
Hello guys! i'm having trouble when i tried to call a custom field,someone could help me with that? my code is below!

<apex:page renderAs="pdf" standardcontroller="Opportunity" applyhtmltag="false" showHeader="false">
<head>
    <style type="text/CSS">
  
    .QuoteText{
        text-align:left;
        font-family:"Arial Black",Arial,sans-serif;
        font-size:12px;
      
    }
    .headerRow{
        border: 1px solid black;
    }
    .footerRow{
        border: 1px solid black;
        text-align:right  
    }
    .list{
        border: 1px solid black;
        border-collapse:collapse;
        font-family:"Arial Black",Arial,sans-serif;
        font-size:12px;
      
    }
    .coluna{
        border: 1px solid black;
      
    }
   
    @page {
         /* Landscape orientation */
         /*size:landscape;*/
      
         /* Put page numbers in the top right corner of each
            page in the pdf document. */
         @bottom-right {
         content: "Página " counter(page) " de " counter(pages);
         }
     }
    </style>
</head>
    <body>
    <apex:form id="theForm">
    <table border="1" >
    <tr><td><img src="/servlet/servlet.FileDownload?file=015e00000007hNZ" border="0" height="32" align="left" /></td><td></td></tr>
    </table>
    <table border="1" >
    <tr><td><p class="QuoteText"> <b>CNPJ:</b></p></td><td></td></tr>
    <tr><td><p class="QuoteText"> <b>Cliente:</b></p></td><td><b>C2W Code:</b>&nbsp;{!Opportunity.Contrato__c}</td></tr>
    <tr><td><p class="QuoteText"> <b>Cotação:</b> {!Opportunity.StageName}</p></td><td></td></tr>
    <tr><td><p class="QuoteText"> <b>Data de Emissão:</b> </p></td><td><apex:outputText value="{0,date,dd'/'MM'/'yyyy}"><apex:param value="{!Opportunity.Sumario__c}" /> </apex:outputText></td></tr>
    <tr><td><p class="QuoteText"> <b>Data de Validade:</b> </p></td><td>a Definir</td></tr>  
    </table>      

      
  <apex:pageBlock >
         <p class="QuoteText">Prezado <apex:outputText value="{}" /> <br /><br />
         Primeiramente, agradecemos sua preferência, lembrando que a C2W oferece opções estratégicas para todas as etapas da cadeia<br />
         logística, através de suas divisões C2W Exclusive, C2W Range e C2W Alliance.<br />
         Consulte-nos! Será uma honra participar de suas busca por melhoria cotínua e redução de custos.<br /><br />
         Baseados em suas informações, oferecemos a competitiva opção de tarifa:<br />
         </p>
        </apex:pageBlock>      
        <br></br>
    <table border="1" >
    <tr>
     <td>Escopo de Negócio</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
     <td></td>
     <td></td>
    </tr>
    <tr>
     <td>Modo de Transporte</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
     <td>Tipo de Transporte</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
    </tr>
    <tr>
     <td>Origem</td>
     <td><apex:outputText value="{!Opportunity.Origem__r.Name}"></apex:outputText></td>
     <td>Destino</td>
     <td><apex:outputText value="{!Opportunity.Destino__r.Name}"></apex:outputText></td>
    </tr>
    <tr>
     <td>Incluir serviço de escolta</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
     <td>Serviço de Escolta</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
    </tr>
    </table>
  
    <br></br>
    <table border="1" >
    <tr>
     <td>Descricao</td>
     <td><apex:outputText value="{!Opportunity.Descricao__c}"></apex:outputText></td>
     <td>Tipo de Embalagem</td>
     <td><apex:outputText value="{!Opportunity.TipoEmbalagem__c}"></apex:outputText></td>
    </tr>
    <tr>
     <td>Tipo de Contâiner</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
     <td>Tamanho do Contâiner</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
    </tr>
    <tr>
     <td>Quantidade</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
     <td></td>
     <td></td>
    </tr>
    <tr>
     <td>Cubagem</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
     <td>Comprimento</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
    </tr>
    <tr>
     <td>Peso (kg)</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
     <td>Largura</td>
     <td></td>
    </tr>
    <tr>
     <td>Valor FOB</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
     <td>Altura</td>
     <td><apex:outputText value="{!Opportunity.SolicitacaoCotacao__r}"></apex:outputText></td>
    </tr>
    </table>  
        <apex:pageBlock >
         <p class="QuoteText">Condições Gerais:<br /><br />
         1. Pagamento:&nbsp;&nbsp;&nbsp;<apex:outputText value="{0,number,###}"><apex:param value="{!Opportunity.PrazoPagamento__c}" /></apex:outputText> dias<br />
         2. Seguro: 0,10% até RS 300.000,00 // 0,20% de R$ 300.000,01 até R$ 600.000,00. Acima de R$ 600.000,00 sob consulta<br />
         3. Pedágio: oficial<br />
         4. Taxa de DTA: R$ 150,00 / viagem<br />
         5. Descarga / Carregamento: por conta do cliente<br />
         6. Carregamento e/ou entrega em Cubatão ou São Vicente R$ 180,00 / viagem<br />
         7. Carregamento e/ou entrega no Guarujá, Praia Grande ou Área Continental de São Vicente R$ 260,00 / viagem<br />
         8. Estadia para descarga: Franquia de 4 horas, após o que se aplica R$ 70,00 / hora<br />
         9. ISS/ICMS: conforme legislação tributária em vigor<br />
         10. Veiculo LS (para peso acima de 25 tons) - adicionar 15% sobre o valor do frete<br />
         <br />
         Conforme entendimentos, notem que esta cotação contempla 20% (vinte por cento) sobre o total líquido da (nomear por extenso.<br />
         Em cotações, siglas só devem ser usadas para impostos) GR/sobre todos os itens de serviço a título da comissão, excetuando-se<br />
         os impostos e repasses. Outras cobranças: caso sejam solicitados serviços adicionais os valores serão cobrados conforme<br />
         proposta. Cotação válida por 15 dias úteis a partir de <apex:outputText value="{0,date,dd'/'MM'/'yyyy}">
                      <apex:param value="{!TODAY()}" />
                 </apex:outputText>
<br /><br /><br />
       
         Identificação: <apex:outputText value="{!Opportunity.Owner.Name}" /><br /><br /><br />
       
         <img src="/servlet/servlet.FileDownload?file=015e00000007hNe" height="32" />, C2W Range e C2W Alliance
         </p>
        </apex:pageBlock>
    </apex:form>
    </body>
</apex:page>
I am totally new at coding apex. I managed to write the code but I have a lot of unanswered questions about how to write the test. Below is the code I need to write the test for and below that is what I have written so far for the test. What is happening in the code is I have a Dedicated Stock (DS) parent object (It contains 8 product manager fields used for an approval process). The DS parent object has a relationship to the SR_Products child objects (0-many). The product child records contain one product manager field and it is filled depending on who the product manager is for the product selected. When an insert or update is done to the SR_Products record the trigger runs to fill in the corresponding product manager field on the parent DS object. The trouble I am having with writing the test is (basically I don't know much here): 1) In the test what happens with formula fields? The child object contains formula fields that are key to the test. Don't know how to fill those. 2)Do you have to put test data in for the parent, child, and user objects. 3) Do I use real Id numbers or how do I set that up? What would I do the assert on? Any help to get me going is appreciated.

trigger SR_Set_Approvers on SR_Products__c (After insert, After Update) {

    // This trigger sets all the product managers from the Stocking Request records
    // With the data from the SR - Product Details records
   
    // Loop all product records that have changed
    for (SR_Products__c prod : Trigger.new) {
       
     system.debug('product name1 = ' + prod.Stocking_Request__c);
        // Get all the product records related to the SR
        SR_Products__c[] allproducts = [SELECT product_manager__c, PM_Type__C,
                                        stocking_request__c
             FROM SR_Products__c
             WHERE stocking_request__c = :Prod.stocking_request__c 
             ];
        String Pm1 = '';
        String Pm2 = '';
        String Pm3 = '';
        String Pm4 = '';
        String Pm5 = '';
        String Pm6 = '';
        String Pm7 = '';
        String Pm8 = '';
   //Set the PM variables with the PM from the SR-Products records       
     for(SR_Products__c p : allproducts) {
       
   If (p.PM_Type__c == 'PM1')
                pm1 = p.product_manager__c;
            If (p.PM_Type__c == 'PM2')
                pm2 = p.product_manager__c;
            If (p.PM_Type__c == 'PM3')
                pm3 = p.product_manager__c;
            If (p.PM_Type__c == 'PM4')
                pm4 = p.product_manager__c;
            If (p.PM_Type__c == 'PM5')
                pm5 = p.product_manager__c;
            If (p.PM_Type__c == 'PM6')
                pm6 = p.product_manager__c;
            If (p.PM_Type__c == 'PM7')
                pm7 = p.product_manager__c;
            If (p.PM_Type__c == 'PM8')
                pm8 = p.product_manager__c;                   
        } //end loop products
       
        // Get the Stocking Request record
        system.debug('product name = ' + prod.Stocking_Request__c);
        Stocking_Request__c sr = [Select ID, Name,
                               Product_Manager_1__c, Product_Manager_2__c,
                               Product_Manager_3__c, Product_Manager_4__c,
                               Product_Manager_5__c, Product_Manager_6__c,
                               Product_Manager_7__c, Product_Manager_8__c
                     From Stocking_Request__c
                     Where ID = :prod.Stocking_Request__c];
       
      // Reset all PM fields to blank to start out with
      sr.Product_Manager_1__c = null;
        sr.Product_Manager_2__c = null;
        sr.Product_Manager_3__c = null;
        sr.Product_Manager_4__c = null;
        sr.Product_Manager_5__c = null;
        sr.Product_Manager_6__c = null;
        sr.Product_Manager_7__c = null;
        sr.Product_Manager_8__c = null;
        // Get the user record IDs for the PM variable fields
        // And set the PM fields in the stocking request record
       system.debug('pm1 ID using =  ' + pm1 + pm2);
        If (PM1 != '' ){
         User u1 = [Select ID, Name
                     From User
                     Where Name = :PM1];           
            If (u1 != null)sr.Product_Manager_1__c = u1.ID;
        } //End PM1 if
       
  system.debug('pm2 ID using =  ' + pm2);
        If (PM2 != '' ){
         User u2 = [Select ID, Name
                     From User
                     Where Name = :PM2];
            If (u2 != null)sr.Product_Manager_2__c = u2.id;
        } //End PM2 if       
  system.debug('pm3 ID using =  ' + pm3);
        If (PM3 != '' ){
         User u3 = [Select ID, Name
                     From User
                     Where Name = :PM3];
            If (u3 != null)sr.Product_Manager_3__c = u3.id;
        } //End PM3 if
        system.debug('pm4 ID using =  ' + pm4);
        If (PM4 != ''){
         User u4 = [Select ID, Name
                     From User
                     Where Name = :PM4];
            If (u4 != null)sr.Product_Manager_4__c = u4.id;
        } //End PM4 if       
        system.debug('pm5 ID using =  ' + pm5);
        If (PM5 != '' ){
         User u5 = [Select ID, Name
                     From User
                     Where Name = :PM5];
            If (u5 != null)sr.Product_Manager_5__c = u5.id;
        } //End PM5 if       
       
        If (PM6 != ''){
         User u6 = [Select ID, Name
                     From User
                     Where Name = :PM6];
            If (u6 != null)sr.Product_Manager_6__c = u6.id;
        } //End PM6 if       
 
        If (PM7 != '' ){
         User u7 = [Select ID, Name
                     From User
                     Where Name = :PM7];
            If (u7 != null)sr.Product_Manager_7__c = u7.id;
        } //End PM7 if       

        If (PM8 != '' ){
         User u8 = [Select ID, Name
                     From User
                     Where Name = :PM8];
            If (u8 != null)sr.Product_Manager_8__c = u8.id;
        } //End PM8 if       
       Update sr;
      
}  // End for looping of changed product records
}


My test so far:

@IsTest

Private class TestSRProducts {
   
    static TestMethod void AddProduct() {
        //Setup new Stocking Request
        Stocking_Request__c AR = new Stocking_Request__c();
        AR.Sold_To__c = 'ABC Company';
        AR.Business_Case__c = 'Bus';
       
       
        //Setup new product
        SR_Products__c testAddP = new SR_Products__c();
        testAddp.Stocking_Request__c = 'ABC Company';
        testAddp.Product__c = '01td00000035nAg';
        testAddp.Form__c = 'Web';
        testAddp.Certification__c = 'FSC';
        testAddp.Pounds__c = 10;
        testAddp.Selling_Price__c = 45.00;
        testAddp.New_or_Existing__c = 'New';
        testAddp.width__c = 12;
        testAddp.Diameter__c = 12;
        testAddp.length__c = 24;
        testaddp.Core_Size__c = 24;
        testaddp.Grain__C = 'Long';
        testaddp.Pounds_Per__c = 'Month';
        Test.startTest();
        insert testaddp;
        Test.stoptest();
       System.assertnotEquals(testaddp.id, null);
      
    } //End AddProduct
       
       
       
} //End Class TestSRProducts