• _
  • NEWBIE
  • 60 Points
  • Member since 2011

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 37
    Replies

Hello guys,

 

I am writing a test class on a trigger and getting 100% code coverage. But I am not able to check the bulk trigger. Can anyone help me include bulk in this test class. Both my trigger and test class is given below. The trigger fetches the associated agency with the contest, and update the agency record with the contest id.

 

Trigger:

 

trigger Tgr_Contests_After on Contests__c (after insert, after update) {
    Map<ID, ID> mapContestAccount = new Map<ID, ID>();
        // get the information of the inserted contest records
        for(Contests__c contest:trigger.new){
            if(contest.agency__c != null){
                mapContestAccount.put(contest.agency__c, contest.id);               
            }
        }
    }
    // get the account information for the loaded contest records
    List<Account> lstAccount = [select contests__c from Account where id in: mapContestAccount.keySet() limit 10000];
    List<Account> lstAccToBeUpdated = new List<Account>();
    // iterate the accounts for updating the contest lookup
    for(Account acc : lstAccount){
        acc.Contests__c = mapContestAccount.get(acc.id);
        lstAccToBeUpdated.add(acc);
    }
    // check if the lstAccToBeUpdated is not empty
    if(!lstAccToBeUpdated.isEmpty()){
        update lstAccToBeUpdated;
    }
}

 

Test class :

 

@isTest(seeAllData=true)
private class Tgr_Contests_After_Test {

    static testMethod void myUnitTest() {
    
    Account acc=TestDataFactory.createtestaccount();  
    insert acc;    
acc= [Select Id from Account where Id = :acc.Id];

              // test data for contests
        Contests__c contest = TestDataFactory.createContest();
        contest.Agency__c = acc.id;

               insert contest;
acc= [Select Id,contests__c from Account where Id = :acc.Id];
contest= [Select Id,agency__c from Contests__c where Id = :contest.id];

        system.assertEquals(contest.id,acc.contests__c);
    }
}

  • April 07, 2013
  • Like
  • 0

Hi all,

 

I developed a functionality that makes use of HttpRequest class. In order to test it I used HttpCalloutMock. This functionality is withing a @future (callout=true) method. I developed the test classes following the documentation for HttpCalloutMock. The tests (2) pass in sandbox, but when deploying to production they both give error System.NullPointerException (apparently the HttpResponse is null) in the assertion line. Here is the code for the tests and the implementations for HttpCalloutMock within the same Test class:

 

@isTest
global class TrustCalloutTest {
    
    global class TrustCalloutMockBasicCallout implements HttpCalloutMock {
        
        global HTTPResponse respond(HTTPRequest req) {
            
            HttpResponse res = new HttpResponse();
            res.setBody('TEST');
            res.setStatusCode(200);
            return res;
        }
    }
    
    global class TrustCalloutMockRequestKey implements HttpCalloutMock {
        
        global HTTPResponse respond(HTTPRequest req) {
            
            HttpResponse res = new HttpResponse();
            res.setBody('RECEIVED');
            res.setStatusCode(200);
            return res;
        }
    }
    
    static testmethod void testCalloutRequireKey() {
    	
        HttpResponse res; 
        Test.setMock(HttpCalloutMock.class, new TrustCalloutMockRequestKey());
        res = TrustCallout.requestTransferKey('BLAH','https://beta2.trustpoint.fi/API/requirekey.php');
        System.assertEquals(200, res.getStatusCode());
    }
    static testmethod void testCalloutBasicCallout(){
         
    	HttpResponse res;
        Test.setMock(HttpCalloutMock.class, new TrustCalloutMockBasicCallout()); 
        res = TrustCallout.basicCallout('BLAH','https://beta2.trustpoint.fi/API/committransfer.php');
        System.assertEquals(200, res.getStatusCode());    
    }
}

 

The actual callout works normally, and it also follows the documentation.

 

Endpoints were added at both sides (production and sandbox).

 

Any idea of what is going on?

 

Thanks.

 

MGA.

 

 

I have a date time string from external system that is represented as 10/13/2011 10:36:07 AM

Need to put it in datetime field on sf object. when try to do datetime.parse ('10/13/2011 10:36:07 AM'); it gives me type exception, invalid date time... any workarounds?

  • October 14, 2011
  • Like
  • 0

Does anyone know if there is a new release coming up for IDE? Are there alternatives for force.com ide? 

  • September 28, 2011
  • Like
  • 0

Does anyone else experience slowness when try refresh or create new project in Force.com Ide? Mine takes 10 minutest to do so... I tried different comuters, different networks... all the same... production is on summer'11 and works fine...

  • September 23, 2011
  • Like
  • 0

What does it mean? 

 

I am trying to do remote javascripting in visualforce. Controller is setup, but when I call function, javascript debugger in chrome gives me this error... function does not take any parameters and simply returns 'Hello' string when is called... Any help would be great.

  • June 29, 2011
  • Like
  • 0
Need help on creating Test class for below Class?
Urgent Help please on this

public class OpportunityUpdateEmailHelper{
public static void  updatePrimaryEmailtoOpportunity(List<opportunity> ops)
   {
   for(opportunity opp:ops)
     {
      if(opp.StageName=='Closed Won')
      {
      system.debug('$****************:'+opp.StageName+'::');
String wonOppId=opp.id;
List<OpportunityContactRole> availablecontacts = [SELECT Id, ContactId, OpportunityId from OpportunityContactRole where OpportunityId = :wonOppId AND IsPrimary=true];
if (availablecontacts.size()==0) return;
system.debug('$****************:'+availablecontacts[0].contactId+'::');

String primarycontactId=availablecontacts[0].contactId;

List<Contact> availablecontact = [SELECT Id, Email from Contact where Id = :primarycontactId];




if (availablecontact.size()==0) return;

system.debug('$****************:'+availablecontact[0].Email+'::');
String sendemailto=availablecontact[0].Email;
opp.Primary_Contact_Email__c=sendemailto;

}
}
}

}

Hi,

I am new to webservices,

while integrating applications In apex how to call external webservices and how to cosume it  in our app.

 

can you help to come  out of this .

 

 

Thanks,

Sarvesh......

 

I've created my first Trigger (yay me) to automatically update a picklist field on a custom Policy object to "Pending" when a task has been created with something selected from the custom "Type_of_Action" field.  I've also written a test class; however I'm getting an error:  "System.AssertException: Assertion Failed: Expected: Pending, Actual: Null"

 

Below is the Trigger and Test Class - any help would be greatly appreciated.

 

 

trigger policyStatusUpdate onTask (beforeinsert, beforeupdate) {

String desiredNewPolStatus = 'Pending';

 

    List<Id> polIds=new List<Id>();

    for(Task t:trigger.new) {

        if (t.IsClosed==FALSE){

            if(String.valueOf(t.whatId).startsWith('a06d') && (t.Type_of_Action__c != null)==TRUE) {//check if the task is associated with a policy

                polIds.add(t.whatId);

            }//if 2

        }//if 1

    }//for

    List<Policy__c> polToUpdate=[SELECT Id, Status__c FROM Policy__c WHERE Id IN :polIds];

    For (Policy__c l:polToUpdate){

        l.Status__c=desiredNewPolStatus;

    }//for

    

    try{

        update polToUpdate;

    }catch(DMLException e){

        system.debug('Policies were not all properly updated.  Error: '+e);

    }

}

 

TEST CLASS:

 

@isTest

 

private class policyStatusUpdate { 

 

    static testMethod void myUpdateTest() {

//CREATE A POLICY RECORD 

    Policy__c aDS = new Policy__c(name='TestPolicy1', Policy_Holder_Name__c='001d000000AoHIr');

    insert aDS; 

 

//CREATE A TASK ASSIGNED TO THE POLICY

        Task t1 = new Task(subject='testupdate 1', WhatId = aDS.id, description = 'test description', Type_of_Action__c='Medicals');     

 

        insert t1;   

 

//RUN AN ASSERT CALL TO MAKE SURE THAT THE CUSTOM FIELD ON THE POLICY HAS THE VALUE OF PENDING

Policy__c assertToTest = [Select Status__c from Policy__c where id = :aDS.id];

system.AssertEquals('Pending', assertToTest.Status__c);

    

    }

}

Hello guys,

 

I am writing a test class on a trigger and getting 100% code coverage. But I am not able to check the bulk trigger. Can anyone help me include bulk in this test class. Both my trigger and test class is given below. The trigger fetches the associated agency with the contest, and update the agency record with the contest id.

 

Trigger:

 

trigger Tgr_Contests_After on Contests__c (after insert, after update) {
    Map<ID, ID> mapContestAccount = new Map<ID, ID>();
        // get the information of the inserted contest records
        for(Contests__c contest:trigger.new){
            if(contest.agency__c != null){
                mapContestAccount.put(contest.agency__c, contest.id);               
            }
        }
    }
    // get the account information for the loaded contest records
    List<Account> lstAccount = [select contests__c from Account where id in: mapContestAccount.keySet() limit 10000];
    List<Account> lstAccToBeUpdated = new List<Account>();
    // iterate the accounts for updating the contest lookup
    for(Account acc : lstAccount){
        acc.Contests__c = mapContestAccount.get(acc.id);
        lstAccToBeUpdated.add(acc);
    }
    // check if the lstAccToBeUpdated is not empty
    if(!lstAccToBeUpdated.isEmpty()){
        update lstAccToBeUpdated;
    }
}

 

Test class :

 

@isTest(seeAllData=true)
private class Tgr_Contests_After_Test {

    static testMethod void myUnitTest() {
    
    Account acc=TestDataFactory.createtestaccount();  
    insert acc;    
acc= [Select Id from Account where Id = :acc.Id];

              // test data for contests
        Contests__c contest = TestDataFactory.createContest();
        contest.Agency__c = acc.id;

               insert contest;
acc= [Select Id,contests__c from Account where Id = :acc.Id];
contest= [Select Id,agency__c from Contests__c where Id = :contest.id];

        system.assertEquals(contest.id,acc.contests__c);
    }
}

  • April 07, 2013
  • Like
  • 0

Hello Helper

 

I want to force a logged user to do something  before start working .  for this I see 2 options:  

 

A. automatically redirect the user to a visual force page right after login

 

Or 

 

B. display a modal dialog box  on the home tab  like the salesforce "Getting started with Chatter"

 

It would be possible?

any other options/suggestion are welcomed

 

 

Thanks in advance

csbaa

  • April 06, 2013
  • Like
  • 0

I have a csv file that has about 30 custom fields that I need to add to salesforce.  The file has the field type like text(255), Date, Checkbox, and so forth.   Is there any way to import them into salesforce?  I would be interested in any option even if it requires the ide or an app.  Thanks.

I have an inputField which is a decimal, but if the existing value is an integer, I want to strip the decimals (e.g. show 5 instead of 5.00).

 

<apex:inputField value="{!myObject.Field__c}" />

 

Is there a way I can do this?

Hi Everyone,

 

I created a VF form which will seach for REFID__c(unique) field in lead object if it matches it retrives the details from lead.IT is working fine.I'm using this page in the site here while i'm clicking the seach button it is showing mw the Authorization required page.I checked all the permissions object ,fields,Apex class, VF all are correct.Here is my code

 

<apex:page standardController="Lead" extensions="LeadUpdate" showHeader="false" sidebar="false">

<head>
    <style>
        .startStyle{
            font-size:12px;
            font-weight:bold;
            color:red;
        }     
    </style>
</head>
<apex:image id="logo" value="{!$Resource.CompanyLogo}"  style="align: left;" height="75" width="233"/>
  <apex:sectionHeader title="{!Lead.Name}" subtitle="Lead Form"/>
  <apex:form id="frm">
    <div style="width:1400px; padding-left:5%; ">
    <apex:pageBlock mode="edit" id="block">
 
      <apex:pageBlockButtons location="both">
        <apex:commandButton action="{!save}" value="Save Records" rerender="frm"/>
        <apex:commandButton action="{!cancel}" value="Cancel"/>
      </apex:pageBlockButtons>
      <apex:pageMessages escape="false"/>
 
      <apex:pageBlockSection >
        <apex:pageBlockSectionItem >
          <apex:outputLabel for="searchText" style="font-size:14px">RefID/FileNumber</apex:outputLabel>
          <apex:panelGroup >
          <apex:inputText id="searchText" value="{!searchText}"/>
          <apex:commandButton value="Search" action="{!search}" rerender="block" status="status"/>
          </apex:panelGroup>
        </apex:pageBlockSectionItem>
      </apex:pageBlockSection><br/>
 
      <apex:actionStatus id="status" startText="Searching... please wait..."/>
      <apex:pageBlockSection title="Lead Results" id="resultsBlock" columns="1">
        <apex:pageBlockTable value="{!searchResults}" var="Lead" rendered="{!NOT(ISNULL(searchResults))}">
          <apex:column value="{!Lead.Name}" headerValue="LeadName" width="100"/>
          <apex:column value="{!Lead.Street}" headerValue="Street" width="100"/>
          <apex:column value="{!Lead.City}" headerValue="City" width="100"/>
          <apex:column value="{!Lead.State}" headerValue="State" width="100"/>
        
        <!--  <apex:column headerValue="First Name" width="100">
            <apex:inputField value="{!Lead.FirstName}"/>
          </apex:column>
          <apex:column headerValue="Last Name" width="100">
            <apex:inputField value="{!Lead.LastName}"/>
          </apex:column> -->
          
          <apex:column headerValue="Email" width="100" style="font-size:12px">
            <apex:inputField value="{!Lead.Email}"/>
          </apex:column>
          <apex:column headerValue="Phone" width="100">
            <apex:inputField value="{!Lead.Phone}"/>
          </apex:column>
          <apex:column headerValue="Evening Phone" width="100">
            <apex:inputField value="{!Lead.Evening_Phone__c}"/>
          </apex:column>
          <apex:column headerValue="Preferred Call Time" width="100">
            <apex:inputField value="{!Lead.Preferred_Call_Time__c}"/>
          </apex:column>
          <apex:column headerValue="Notes" width="100">
            <apex:inputField value="{!Lead.Notes__c}"/>
          </apex:column>
          <apex:column headerValue="Do Not Call" width="100">
            <apex:inputField value="{!Lead.DoNotCall}"/>
          </apex:column>
          
        </apex:pageBlockTable>
      </apex:pageBlockSection>
    </apex:pageBlock>
    </div>
  </apex:form>
</apex:page>

 

controller

 

public with sharing class LeadUpdate {
 
  private ApexPages.StandardController controller {get; set;}
  public List<Lead> searchResults {get;set;}
  public string searchText {get;set;}
 

  public LeadUpdate(ApexPages.StandardController controller) { }
 

  public PageReference search() {
    String qry = 'select id, name, FirstName, LastName, Status, Ref_ID_File_Number__c, Email, Phone, Street, City, State, Country, PostalCode, TAB_Message__c, Evening_Phone__c, Preferred_Call_Time__c, Notes__c from Lead ' +
      'where Ref_ID_File_Number__c =:searchText order by name';
    searchResults = Database.query(qry);
    if(searchResults.size()==0){

       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'<b>Ref ID could not be found. The syntax is always as follows: AANNNN-NNNNN (A= Alpha/Letter; N= Number) i.e. FL0301-12345</b>'));
       return null;    
    }else{
    
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info,'<b>Please confirm name and address below. Address will be where the letter was received/addressed. If these do not match, you will need to re-verify Ref ID, as it may have been entered incorrectly</b>'));
       return null;
    }
    return null;
  }
 

  public PageReference save() {
   
   if(!(String.isEmpty(searchText))){
          
       try {
      
         list<lead> lstupdate = new list<lead>();
             
             For(Lead le:searchResults){
             
             //le.Id = lead.Id;
             le.Ref_ID_File_Number__c = searchResults[0].Ref_ID_File_Number__c ;
             le.FirstName = searchResults[0].FirstName;
             le.LastName = searchResults[0].LastName;
             le.Email = searchResults[0].Email;
             le.Status = 'Missed Call';
             le.Phone = searchResults[0].Phone;
             le.Evening_Phone__c = searchResults[0].Evening_Phone__c ;
             le.Preferred_Call_Time__c = searchResults[0].Preferred_Call_Time__c;
             le.Notes__c = searchResults[0].Notes__c;
             le.DoNotCall = searchResults[0].DoNotCall;
             le.TAB_Message__c = True;
             le.TAB_Timestamp__c = System.now();
             lstupdate.add(le);
             }
             
             update lstupdate;
      
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.info,'Record <b>'+searchResults[0].Name+'</b> has been Updated'));
            //creating a task
            Task tsknew = new Task();
            tskNew.WhoId =searchResults[0].id;
            tskNew.Subject = 'Call';
            insert tsknew; 
            
    } Catch (DMLException e) {
      ApexPages.addMessages(e);
      return null;
    }
   
    searchText='';
    searchResults.clear(); 
    return null;
       
  }
  else
  {
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.info,'Please enter REFID/FileNumber'));
  }
  
  return null;
 
}
  public PageReference cancel() {
       
       pageReference pg1 = new pageReference('/apex/leadform1');
       return(pg1.setredirect(true));
       
  }
 
}

 

I get Error: Compile Error: Loop variable must be of type Id at line 39 column 18 for the line for (Account a:AccountsIds){ 

How come? It works for the line for (User u:UserList) {

the debug logs tell me I created the ID in the list AccountsIds properly. 

Please assist, thanks!

 

 

trigger TeamMemberAssignedtoTeam on Coverage_Person__c (after insert) {

/*if the Team Member (coverage_person__c) is a User, link them to that User and add them to the Account Teams to all Accounts the Team is Assigned to. */
//lists

    List < EntitySubscription > esSet = new List < EntitySubscription > ();
    List < Double > empIds = new List < Double > ();
    List < AccountTeamMember > atms = new List < AccountTeamMember > ();
    List < string > CPUsers = new List < string > ();

  //  List < AccountShare > ASSES = new List < AccountShare > ();
    List <id> covTeams = new List <id> ();
  
    //get list of emp ids from the coverage people inserted//
    
    for (Coverage_Person__c p: trigger.new) {
        empIds.add(p.Emp_Id__c);
        covTeams.add(p.Coverage_team__c);
    }
    system.debug('covTeams-----------'+covTeams);
    
    //get the users that match the inserted coverage people via emp id//
        
    List < User > userList = [select id, Emp_Id__c from User where isActive = True and userType='Standard' and EMP_ID__c IN: empIds];
     system.debug('userlist--------------'+userList );
   
    //Get the accounts covered by the team the person was added to
    
    List <Assigned_Team__c> TeamsAccounts = [select Account__c  from Assigned_Team__c where Coverage_Team__c IN: covTeams];
    system.debug('TeamsAccounts-----------'+TeamsAccounts);
    
     list<ID> AccountsIds = new list<ID>();
     
      for(Assigned_Team__c es:TeamsAccounts){AccountsIds.add(es.Account__c);} 
      
    system.debug('accountids--------------'+AccountsIds);
    //add the User to Account Teams for the Accounts
   
    for (Account a:AccountsIds){ 
    for (User u:UserList) {
       
    AccountTeamMember atm = new AccountTeamMember(AccountID=a.id, UserId=u.id,TeamMemberRole='test');
    atms.add(atm);
    }
    }
    
    insert atms;
    
    

}

 

  • February 20, 2013
  • Like
  • 0

Hi all,

 

I developed a functionality that makes use of HttpRequest class. In order to test it I used HttpCalloutMock. This functionality is withing a @future (callout=true) method. I developed the test classes following the documentation for HttpCalloutMock. The tests (2) pass in sandbox, but when deploying to production they both give error System.NullPointerException (apparently the HttpResponse is null) in the assertion line. Here is the code for the tests and the implementations for HttpCalloutMock within the same Test class:

 

@isTest
global class TrustCalloutTest {
    
    global class TrustCalloutMockBasicCallout implements HttpCalloutMock {
        
        global HTTPResponse respond(HTTPRequest req) {
            
            HttpResponse res = new HttpResponse();
            res.setBody('TEST');
            res.setStatusCode(200);
            return res;
        }
    }
    
    global class TrustCalloutMockRequestKey implements HttpCalloutMock {
        
        global HTTPResponse respond(HTTPRequest req) {
            
            HttpResponse res = new HttpResponse();
            res.setBody('RECEIVED');
            res.setStatusCode(200);
            return res;
        }
    }
    
    static testmethod void testCalloutRequireKey() {
    	
        HttpResponse res; 
        Test.setMock(HttpCalloutMock.class, new TrustCalloutMockRequestKey());
        res = TrustCallout.requestTransferKey('BLAH','https://beta2.trustpoint.fi/API/requirekey.php');
        System.assertEquals(200, res.getStatusCode());
    }
    static testmethod void testCalloutBasicCallout(){
         
    	HttpResponse res;
        Test.setMock(HttpCalloutMock.class, new TrustCalloutMockBasicCallout()); 
        res = TrustCallout.basicCallout('BLAH','https://beta2.trustpoint.fi/API/committransfer.php');
        System.assertEquals(200, res.getStatusCode());    
    }
}

 

The actual callout works normally, and it also follows the documentation.

 

Endpoints were added at both sides (production and sandbox).

 

Any idea of what is going on?

 

Thanks.

 

MGA.

 

 

I am writing a trigger where if the region field on the opportunity owner's user record are certain values, to pull those values onto the Region field on the opportunity page, else look to the account owner's user record. I am getting the following error:

 

 

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger OpportunityOwnersAddress2 caused an unexpected exception, contact your administrator: OpportunityOwnersAddress2: execution of BeforeUpdate caused by: System.ListException: List index out of bounds: 0: Trigger.OpportunityOwnersAddress2: line 47, column 13

 

 

This error is at the end of the trigger. I am stared at this ad nausium, and it looks correct to me. But apparently it is not.

Here is the trigger:

 

 

trigger OpportunityOwnersAddress2 on Opportunity (before insert, before update) {

    Set<Id> UserIds = new Set<Id>();
    for (Opportunity oppo: Trigger.new){
    System.debug('**** 0 userids id : '+oppo.ownerid);
    
            UserIds.add(oppo.ownerId);
     System.debug('**** 1 oppo id : '+oppo.id);
     
     }
    
    Map<Id, User> entries = new Map<Id, User>();
    List<user> us = [select Id, User_Address__c, Phone, Fax, Email, Region__c from User where id in :UserIds];
    
    string txt = '';
    txt = us[0].User_Address__c;          
    txt = txt.replaceAll('<br>', '\n');
    System.debug('**** 1 ****txt txt txt txt *********:'+txt );


    string uc = 'US/Canada';
    string euro = 'Europe';
    string Inter = 'InterCon';
    string auc = 'US/Canada';
    string aeuro = 'Europe';
    string aInter = 'InterCon';
        
    for(Opportunity unity: Trigger.new) {
       unity.Opp_Owner_Address__c = txt;
       unity.Opp_Owner_Phone__c = us[0].Phone;
       unity.Opp_Owner_Fax__c = us[0].Fax;
       unity.Opp_Owner_Email__c = us[0].Email;
       
       UserIds.add(unity.ownerId);


    If( us[0].Region__c == uc || us[0].Region__c == euro || us[0].Region__c == Inter ){

       unity.Opportunity_Region__c =us[0].Region__c;
  
      }

    Map<Id, Account> a = new Map<Id, Account>();
    List<Account> ac = [select Id, OwnerId from Account where id =: unity.Accountid];
    List<user> aus = [select Id, Region__c from User where id =: unity.account.ownerid];
    
    If( aus[0].Region__c != auc || aus[0].Region__c != aeuro || aus[0].Region__c != aInter ){

       unity.Opportunity_Region__c = aus[0].Region__c;
    } else {
    unity.Opportunity_Region__c= txt;
    }
  }
}

 

 

How do I solve the error?

 

Thank you,

ckellie