function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
eric_wceric_wc 

unit test failing

Please help I am not a developer but am trying to learn.  After taking code samples from the board and manuals I was able to get this apex class do what I wanted but then I ran into the issue of unit test.  I had a hard enough time figuring out how to get the class to work.  I feel like I am banging my head against a wall with the unit test process it just does not make sense to me.  But I have figured out how to get 80% coverage but it is failing and I am not sure how to fix it.  Any help would be appreciated.

Thanks

Eric

 

Message: System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target object ids (contact, lead or user): []

stack trace: Class.MNEmail2.send: line 56, column 1 Class.MNEmail2.testMNEmail2: line 89, column 32 External entry point

 

 

public class MNEmail2 {
public String Template = [select MN_Email_Template__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Email_Template__c;
public list <Contact> Test;
Contact[] contactList = new Contact[]{};
Id[] targetObjectIds = new Id[] {};
Id[] whatids = new Id[] {}; 
public id mn = [select ID from Case where id = :ApexPages.currentPage().getParameters().get('id')].id; 
public String custaff = [select MN_Customers_Affected__c from Case where id = :ApexPages.currentPage().getParameters().get('id') limit 1].MN_Customers_Affected__c;
String[] actnames = new List<String>();

public MNEmail2() {
actnames = custaff.split(';');
//System.debug ('***** List: ' + actnames + ', size: ' + actnames.size ());
         //Loop thrugh the whole ist of contacts an their emails
          for (Contact c : [Select account.name, name, email from Contact where Contact.Account.name = :actnames and Receive_support_notifications__c = True]) {
            targetObjectIds.add(c.Id);
            contactlist.add(c);
            whatIds.add(mn);
           }
}

//public Account getAccount() {
//return account;
//}
public string getTemplate() {
    return Template;
}
public id getmn() {
    return mn;
} 
 public list<Contact> getcontacts(){ 
        return ContactList;  
}


public PageReference cancel() {
    PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
}

public PageReference send() {
// Define the email
Messaging.MassEmailMessage email = new Messaging.MassEmailMessage();
// Sets the paramaters of the email
email.setTargetObjectIds (targetObjectIds);
email.setWhatIds (whatids);
email.setTemplateId ([select id from EmailTemplate where Name = :template].id);
email.setreplyto ('noreply@demandtec.com');
email.setSenderDisplayName ('DemandTec Support No-Reply');
//email.setSubject( subject );
//email.setToAddresses( toAddresses );
//email.setPlainTextBody( body );
// Sends the email
Messaging.SendEmailResult [] r =
Messaging.sendEmail(new Messaging.MassEmailMessage[] {email});
PageReference pageRef = new PageReference('/'+ mn);
    pageRef.setRedirect(true);
    return pageRef;
return null;
}
static testMethod void testMNEmail2(){
   
        //make test data
        Account a = new Account(Name = 'Testing');
        Insert a;
        Contact con = new Contact(Firstname = 'testing',lastname = 'test',email = 'eric.wc@gmail.com',Receive_support_notifications__c = True,Account = a);
        Insert con;
        Case c = new Case(Subject = 'Test case',MN_Email_Template__c = 'Scheduled Maintenance',MN_Customers_Affected__c = 'Testing');
        Insert c;
       
        CaseComment cmt1 = new CaseComment(
            ParentId = c.id,
            IsPublished = false,
            CommentBody = 'A private comment from a user.'
        );
        CaseComment cmt2 = new CaseComment(
            ParentId = c.id,
            IsPublished = true,
            CommentBody = 'A public comment from a client.'
        );
        Insert cmt1;
        Insert cmt2;
       
         // Initiate class createOpsTicketClass with reference to created Support Case
             System.currentPageReference().getParameters().put('id', c.id);

             MNemail2 ee = new MNemail2();
             String nextPage = ee.send().getUrl();
             nextPage = ee.cancel().getUrl();
             System.assert(ee.mn == c.id);
}

}

 

 

 

Coco_SydneyCoco_Sydney
for (Contact c : [Select account.name, name, email from Contact where Contact.Account.name = :actnames and Receive_support_notifications__c = True])

put Id in query, try does it fix

hitzhitz

hi,eric_wc

 

you need to pass targetObjectId [contact] , whatid [contact.id] and also you need to provide email template id as parameter

eric_wceric_wc

I thought the idea was that those values would be picked up from the case I inserted.

 

Eric

fixifixi

hi i'm facing that problem too

i'm already set the template id and the contactid for targetobjectid

but it still showing required_field_missing

maybe that cause my template need a parameter..

but i don't know how to set it via my API

does anybody know?

hitzhitz

Hi,

 

can u plz share your code ??

fixifixi

Thank you

after some trial and error

i've solved it and get the way to set the parameter

using singleEmail method

 

here is the code using PHP API

i'm modified from http://wiki.developerforce.com/index.php/PHP_Toolkit_11.0_SendEmail_Sample_(Partner)

 

 

 

<?php
// SOAP_CLIENT_BASEDIR - folder that contains the PHP Toolkit and your WSDL
// $USERNAME - variable that contains your Salesforce.com username (must be in the form of an email)
// $PASSWORD - variable that contains your Salesforce.ocm password

define("SOAP_CLIENT_BASEDIR", "soapclient");
require_once (SOAP_CLIENT_BASEDIR.'/SforcePartnerClient.php');
require_once ('userAuth.php');

try {
$mySforceConnection = new SforcePartnerClient();
$mySoapClient = $mySforceConnection->createConnection(SOAP_CLIENT_BASEDIR.'/partner.wsdl.xml');
  $mylogin = $mySforceConnection->login($USERNAME, $PASSWORD);
  
$singleEmail1 = new SingleEmailMessage();
  $singleEmail1->toAddresses = "admin@gmail.com";//the destination mail 
$singleEmail1->saveAsActivity = true;
$singleEmail1->emailPriority = EMAIL_PRIORITY_LOW;
  $singleEmail1->templateId = "00X90000000KWKgEAO";//templateId that we want to use
$singleEmail1->targetObjectId = "00390000005gx66AAA";//contactid
  $singleEmail1->whatId="a0990000000wCXtAAM"; // Id Object Record for email parameter 


echo "***** Send Emails *****\n";
$emailResponse = $mySforceConnection->sendSingleEmail(array ($singleEmail1));
echo "email Response <pre>";
print_r($emailResponse);
echo "</pre>";

} catch (Exception $e) {
echo "error message <pre>";
echo $mySforceConnection->getLastRequest();
echo $e->faultstring;
echo "</pre>";
}
?>

fixifixi

oh ya we cannot set plaintext and subject for our email too

cause it already set in Email Template