Trigger Handler not throwing errors or reading SOQL query correctly - salesforce

When the trigger is called, I'm looking to pass the Trigger.new list into the ContactTriggerHandler class, and then filter on that list to be a certain record type and associated with an Account Contact Relationship (AccountContactRelation object) that has a certain role. This compiles but is not triggering any of the error codes. I passed con directly to the for loop and it works as intended (doesn't check relationships or record type however), so I'm thinking that it may be the SOQL query. When I run the test, I only get 63% code coverage (image below).
Trigger
trigger ContactTrigger on Contact (before update) {
if(trigger.isbefore){
if(trigger.isupdate){
ContactTriggerHandler.IsPricingLetter(Trigger.new);
}//End If IsUpdate
}//End If IsBefore
}//End Class
Class
public class ContactTriggerHandler {
public static void IsPricingLetter(List<Contact> con){
List<Contact> ContactLookup = [SELECT id,mailingstreet,mailingcity,mailingstate,mailingpostalcode,mailingcountry,email,active_contact__c
FROM contact WHERE id IN :con
AND id IN (SELECT Contactid
FROM accountcontactrelation
WHERE roles INCLUDES (:label.messer_US_Pricing_Letter) AND isactive=true)
AND Recordtypeid='0125b0000015OkJAAU'
];
for(Contact CheckContact : ContactLookup){
if(CheckContact.MailingStreet==null){
CheckContact.MailingStreet.addError(label.Messer_US_Contact_Street+' on a '+label.messer_US_Pricing_Letter+' Contact cannot be null.');
}//End If Mailing Street
if(CheckContact.MailingCity==null){
CheckContact.MailingCity.addError(label.Messer_US_Contact_City+' on a '+label.messer_US_Pricing_Letter+' Contact cannot be null.');
}//End If Mailing City
if(CheckContact.MailingState==null){
CheckContact.MailingState.addError(label.Messer_US_Contact_State+' on a '+label.messer_US_Pricing_Letter+' Contact cannot be null.');
}//End If Mailing State
if(CheckContact.MailingPostalCode==null){
CheckContact.MailingPostalCode.addError(label.Messer_US_Contact_Postal_Code+' on a '+label.messer_US_Pricing_Letter+' Contact cannot be null.');
}//End If Mailing Postal Code
if(CheckContact.MailingCountry==null){
CheckContact.MailingCountry.addError(label.Messer_US_Contact_Country+' on a '+label.messer_US_Pricing_Letter+' Contact cannot be null.');
}//End If Mailing Country
if(CheckContact.Email==null){
CheckContact.Email.addError(label.Messer_US_Contact_Email+' on a '+label.messer_US_Pricing_Letter+' Contact cannot be null.');
}//End If Email
if(CheckContact.Active_Contact__c==false){
CheckContact.active_contact__c.addError('A Contact with an active '+label.messer_US_Pricing_Letter+' relationship cannot be made inactive.');
}//End If Active
}//end for loop
}//end isPricingLetter method
}//End Class
Test Class
#isTest
public class ContactTriggerHandlerTest {
public static Account getAccount(){
ccrz__E_AccountGroup__c accountgroupObj = new ccrz__E_AccountGroup__c(Name = 'Messer Base',
CurrencyIsoCode = 'USD',
ccrz__PriceListSelectionMethod__c = 'Best Price');
insert accountgroupObj;
account a = new account(name='DevTest Account',Type='Prospect',Industry='Chemistry & Energy',
ccrz__E_AccountGroup__C=accountgroupobj.id);
insert a;
return a;
}//End getAccount
public static Contact getContact(){
Account a = getAccount();
contact c = new contact(firstname = 'TestFirstName',active_contact__c=true,lastname = 'TestLastName',mailingstreet = 'Test Street',mailingcity = 'Test City',
mailingState = 'Test State',mailingPostalCode = '99999',mailingCountry = 'US',email = 'test#test.com',accountid=a.id
,recordtypeid='0125b0000015OkJAAU');//CRM Contact US Record Type
insert c;
return c;
}//End getContact
static testmethod void updateStreetWithPricingLettersRelationship(){
Contact c = getContact();
Account a = getAccount();
accountcontactrelation acr = new accountcontactrelation(accountid=a.id,contactid = c.id,Roles = label.messer_US_Pricing_Letter,isActive=true);
insert acr;
try{
c.mailingstreet='';
update c;
}catch(DMLException e){
System.debug(e);
}finally{
System.debug('Mailing Street Checked!');
}
}//End updateStreetwithRelationship
static testmethod void updateCityWithPricingLettersRelationship(){
Contact c = getContact();
Account a = getAccount();
accountcontactrelation acr = new accountcontactrelation(accountid = a.Id,contactid = c.id,Roles = label.messer_US_Pricing_Letter,isActive=true);
insert acr;
try{
c.mailingcity='';
update c;
}catch(DMLException e){
System.debug(e);
}finally{
System.debug('Mailing City Checked!');
}
}//End updateCitywithRelationship
static testmethod void updateStateWithPricingLettersRelationship(){
Contact c = getContact();
Account a = getAccount();
accountcontactrelation acr = new accountcontactrelation(accountid = a.Id,contactid = c.id,Roles = label.messer_US_Pricing_Letter,isActive=true);
insert acr;
try{
c.MailingState='';
update c;
}catch(DMLException e){
System.debug(e);
}
finally{
System.debug('Mailing State Checked!');
}
}//End updateStatewithRelationship
static testmethod void updatePostalCodeWithPricingLettersRelationship(){
Contact c = getContact();
Account a = getAccount();
accountcontactrelation acr = new accountcontactrelation(accountid = a.Id,contactid = c.id,Roles = label.messer_US_Pricing_Letter,isActive=true);
insert acr;
try{
c.MailingPostalCode='';
update c;
}catch(DMLException e){
System.debug(e);
}
finally{
System.debug('Mailing Postal Code Checked!');
}
}//End updatePostalCodewithRelationship
static testmethod void updateCountryWithPricingLettersRelationship(){
Contact c = getContact();
Account a = getAccount();
accountcontactrelation acr = new accountcontactrelation(accountid = a.Id,contactid = c.id,Roles = label.messer_US_Pricing_Letter,isActive=true);
insert acr;
try{
c.MailingCountry='';
update c;
}catch(DMLException e){
System.debug(e);
}finally{
System.debug('Mailing Country Checked!');
}
}//End updateCountrywithRelationship
static testmethod void updateEmailWithPricingLettersRelationship(){
Contact c = getContact();
Account a = getAccount();
accountcontactrelation acr = new accountcontactrelation(accountid = a.Id,contactid = c.id,Roles = label.messer_US_Pricing_Letter,isActive=true);
insert acr;
try{
c.Email='';
update c;
}catch(DMLException e){
System.debug(e);
}finally{
System.debug('Email Checked!');
}
}//End updateEmailwithRelationship
static testmethod void DeactivateContactAttempt(){
Contact c = getContact();
Account a = getAccount();
accountcontactrelation acr = new accountcontactrelation(accountid = a.Id,contactid = c.id,Roles = label.messer_US_Pricing_Letter,isActive=true);
insert acr;
try{
c.Active_Contact__c=false;
update c;
}catch(DMLException e){
System.debug(e);
}finally{
System.debug('Active Contact? Checked!');
}
}//End updateEmailwithRelationship
}//End Class

Mate, I gave you a decent answer in https://stackoverflow.com/a/75140042/313628
I explained that your stuff doesn't run OK because you're running a loop over what you queried from database - over old values, from before save action you're intercepting now. Nothing you're updating "right now" in the trigger is checked in that loop. In fact it's extra dummy because if user inserts a Contact with empty address - your thing will happily prevent them from ever fixing that.
Then we had https://stackoverflow.com/a/75188127/313628
And now this... So yeah, technically I suspect this will give you coverage:
Contact c = new Contact(AccountId = '...', LastName = 'whatev'); // yes, empty address
insert c;
insert new AccountContactRelation(...);
try{
c.MailingStreet = c.MailingCity = c.MailingCountry = c.MailingPostalCode = 'unimportant';
update c;
} catch(Exception e){
System.assert(e.getMessage().contains(Label.Messer_US_Contact_Street));
// Oops, this throws even when I'm trying to fix the missing data!
}
Don't deploy this to production, you'll brick your system...

Related

After Update in Apex Class - Total Contacts "Roll-Up Summary"

I added the Apex Class and Apex trigger below to update the field Number_of_Contacts at the Account level when a Contact is added or removed to a certain Account.
My idea is to display in Accounts reports, how many Contacts an Account has. I had to do this, because Salesforce doesn't provide a Roll-Up Summary, at the Account level, to count Contacts.
I also tried creating a Flow, but it only works when a Contact is created or deleted.
Here are Apex Class and Trigger I tried to use:
Class:
public without sharing class ContactTriggerHandler {
private Set<Id> getAccountIds(List<Contact> contacts) {
Set<Id> accountIds = new Set<Id>();
for(Contact c : contacts) {
if(c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
return accountIds;
}
private Map<Id, Account> getAccountMap(Set<Id> accountIds) {
return new Map<Id, Account>([SELECT Id, Number_of_Contacts__c FROM Account WHERE Id in :accountIds]);
}
public void process(List<Contact> contacts, System.TriggerOperation operation) {
Set<Id> accountIds = getAccountIds(contacts);
if(accountIds.size() > 0) {
Map<Id, Account> accountMap = getAccountMap(accountIds);
for(Contact c : contacts) {
if(accountMap.containsKey(c.AccountId)) {
switch on operation{
when AFTER_INSERT {
accountMap.get(c.AccountId).Number_of_Contacts__c += 1;
}
when AFTER_DELETE {
accountMap.get(c.AccountId).Number_of_Contacts__c -= 1;
}
when AFTER_UNDELETE {
accountMap.get(c.AccountId).Number_of_Contacts__c += 1;
}
}
}
}
update accountMap.values();
}
}
}
Trigger
trigger ContactTrigger on Contact (after insert, after delete, after undelete) {
ContactTriggerHandler handler = new ContactTriggerHandler();
switch on Trigger.operationType {
when AFTER_INSERT {
handler.process(Trigger.new, Trigger.operationType);
}
when AFTER_DELETE {
handler.process(Trigger.old, Trigger.operationType);
}
when AFTER_UNDELETE {
handler.process(Trigger.new, Trigger.operationType);
}
}
}
However, how can I include a line of code that updates the Number_of_Contacs__c field when a Contact moves to a different Account (like, an "After_Update" trigger)?
Thank you,
I tried some guidance on how to add AFTER UPDATE triggers in Apex Code, but I didn't succeed.
Trigger context variables give you access to old and new values, state of the database before the user clicked save and what the user has changed. You're passing from trigger to class only trigger.new but to get the id of original account the contact was linked to and update it - something like this.
Set<Id> idsToCheck = new Set<Id>();
// During update, only if account id changes...
for(Contact c : trigger.new){
Contact old = trigger.oldMap.get(c.Id);
if(c.AccountId != old.AccountId){
idsToCheck.add(c.AccountId);
idsToCheck.add(old.AccountId); // mark both for further processing
}
}
idsToCheck.remove(null);
List<Account> accounts = [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :idsToCheck];
for(Account a : accounts){
a.Number_of_Contacts__c = a.Contacts.size();
}
update accounts;

Write test class for apex(salesforce)

I write code for Apex trigger, now i need to test him. Can u help me?
here is the code:
public with sharing class Sharing_Sales {
public static void SharingRelatedOrdersAndAccount(List<Sales_Rep_Assignment__c> triggerNew,
Map<Id, Sales_Rep_Assignment__c> oldMap){
List<Order> relatedOrders = new List<Order>();
List<Sales_Rep_Assignment__c> activeAssignments = new List<Sales_Rep_Assignment__c>();
Set<Id> accIds = new Set<Id>();
Set<Id> salesRepsIds = new Set<Id>();
Map<Id, List<Order>> ordersByAccountId = new Map<Id, List<Order>>();
for(Sales_Rep_Assignment__c sar: triggerNew){
if(sar.Active__c == true && (oldMap.get(sar.id).Active__c == false || oldMap == null)) {
activeAssignments.add(sar);
salesRepsIds.add(sar.Sales_Reps__c);
accIds.add(sar.Account__c);
}
for(Order ord : [SELECT Id, AccountId FROM Order WHERE AccountId IN :accIds]) {
if (!ordersByAccountId.containsKey(ord.AccountId)) {
ordersByAccountId.put(ord.AccountId, new List<Order>());
}
ordersByAccountId.get(ord.AccountId).add(ord);
}
List<OrderShare> sharingRecords = new List<OrderShare>();
for (Sales_Rep_Assignment__c srs : activeAssignments) {
for (Order ord : ordersByAccountId.get(srs.Account__c)) {
OrderShare sharingorderrecord = new OrderShare();
sharingorderrecord.OrderId = ord.Id;
sharingorderrecord.OrderAccessLevel = 'Edit';
sharingorderrecord.UserOrGroupId = 'Sales_Rep__c';
sharingorderrecord.RowCause = 'Manual';
sharingRecords.add(sharingorderrecord);
}
if(!sharingRecords.IsEmpty()){
insert sharingRecords;
}
}
}
}
public static void Sharingorderandaccountisdelete(List<Sales_Rep_Assignment__c> triggerNew,
List<Order> relatedOrders,
Map<id, Sales_Rep_Assignment__c> oldMap){
List<Sales_Rep_Assignment__c> falseAssignments = new List<Sales_Rep_Assignment__c>();
Set<Id> accIds = new Set<Id>();
Set<Id> salesRepsIds = new Set<Id>();
Map<Id, List<Order>> ordersByAccountId = new Map<Id, List<Order>>();
for(Sales_Rep_Assignment__c sar: triggerNew){
if(sar.Active__c == false && oldMap.get(sar.id).Active__c == true || triggerNew == null){
falseAssignments.add(sar);
salesRepsIds.add(sar.Sales_Reps__c);
accIds.add(sar.Account__c);
}
}
List<OrderShare> sharingDeletedOrder = new List<OrderShare>();
for(Order ord : [SELECT Id, AccountId FROM Order WHERE AccountId IN :accIds]) {
if (!ordersByAccountId.containsKey(ord.AccountId)) {
ordersByAccountId.put(ord.AccountId, new List<Order>());
}
for(OrderShare sharingRecords: [SELECT Id FROM OrderShare WHERE Id =: ord.id AND UserOrGroupId IN :salesRepsIds]){
sharingDeletedOrder.add(sharingRecords);
}
}
delete sharingDeletedOrder;
}
}`
deskp of task Use
Apex Trigger to share Account and related Orders to Sales Rep when new Sales Rep Assignment is created.
When Sales Rep Assignment record is deleted or set to Active = false Sales Rep should not have edit access to account and related orders anymore, if Active is set back to true – share records again.
You have to create a test class. Here you will find some guidance:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
After you worked it through and wrote a test class, we can help with problems.

Test Class For Appval Process Salesforce

I create this controller to diplay on a visualforce page a custom approval related list of record with the signature (photo) of Actor for an object Called Car_Maintenance. It works perfectly on my sandbox but i have trouble to write the test Class to deploy it in the production.
The Controller and my test class are below. My headache start at the line 53 in the Test Class. the error message is some field are required in the approval record.
Controller
public MaintenanceRequestController() {
}
public Map<Id,User> userMap { get; set; }
public List<ProcessInstanceStep> processInstanceList { get; set; }
public MaintenanceRequestController(ApexPages.StandardController controller) {
userMap = new Map<Id, User>();
processInstanceList = new List<ProcessInstanceStep>();
Id recordId = ApexPages.CurrentPage().getparameters().get('id');
processInstanceList = [Select id,ActorId, Actor.Name,CreatedDate, Actor.Title, Actor.FirstName , ProcessInstanceId,
Actor.LastName, StepStatus, ProcessInstance.TargetObjectId
from ProcessInstanceStep
WHERE ProcessInstance.TargetObjectId = :recordId];
for (ProcessInstanceStep step : processInstanceList){
userMap.put(step.ActorId, new User(Signature__c=null));
}
userMap.putAll([SELECT Id,Name,Signature__c FROM User WHERE Id = :userMap.keySet()]);
}
}```
test Class
```#IsTest
public class CarMaitenanceControllerTest{
static testMethod void CarMaitenanceController(){
Car__c veh = new Car__c ( Category__c='Pickup', Color__c='Red', Condition__c='Excellent',
Description__c='Test Vehicle', Engine_Number__c='XXX',
Matriculation__c = 'IT-00011', Make__c='Toyota', Year__c ='2017', Model__c='Colorado');
insert veh;
Part_Accessories_Reception__c par = new Part_Accessories_Reception__c();
par.Date__c = System.today();
par.Provider__c = 'Other';
insert par;
Part_Accessories__c pa = new Part_Accessories__c(Name = 'filter');
insert pa;
Part_Accessories_Inventory__c pai = new Part_Accessories_Inventory__c();
pai.Quantity_Received__c =7771;
pai.Part_Accessories_Reception__c = par.ID;
pai.Part_Accessories__c = pa.Id;
insert pai;
Car_Maintenance__c carMain = new Car_Maintenance__c();
carMain.Car__c = veh.ID;
carMain.Cheque_Bank__c = '444-Cmmm';
carMain.Company__c = 'FFP';
carMain.Date__c = System.today();
insert carMain;
Maintenance_Details__c mdet = new Maintenance_Details__c();
mdet.Description__c = 'qiuyiuyi';
mdet.Quantity__c =555;
mdet.Maintenance__c = carMain.Id;
mdet.Description__c ='kjalhsdhfklasdf';
mdet.Cost__c = 999;
mdet.Part_Accessories_Inventory__c = pai.Id;
insert mdet;
Approval.ProcessSubmitRequest app = new Approval.ProcessSubmitRequest();
app.setObjectId(carMain.Id);
Approval.ProcessResult result = Approval.process(app);
ProcessInstance pi = new ProcessInstance ();
pi.TargetObjectId = carMain.Id;
pi.Status ='Approved';
Insert pi;
ProcessInstanceStep pis = new ProcessInstanceStep();
pis.ProcessInstanceId = pi.Id;
Insert pis;
Test.setCurrentPageReference(new PageReference('CarMaintenanceView'));
System.currentPageReference().getParameters().put('id', veh.ID);
CarMaintenanceController CRC = new CarMaintenanceController();
MaintenanceRequestController mrc = new MaintenanceRequestController();
}
}```
Can you identify which is line 53 of the test class, the one that is giving you trouble? And the specific error?
It may be that the required fields in production are different than what's in the sandbox, and that's tripping you up when you insert your test data.

System.TypeException: Invalid integer salesforce test class error in controller

i have a visual force page which is used as a view to send a custom sms to the leads generated in salesforce.The year field is a number field on salesforce. Posting the controller and test class error. Also mentioning the error line.
Controller :-
//Class to send Message to Lead or Account
public class nmSendSMS
{
//Name of Lead or Account
public string strName{get;set;}
public Lead objLead {get;set;}
public String defaultNumbersToBeAdded;
public String leadYear{get;set;}
//Mobile number of lead of account
public string strMobile{get;set;}
public String messageToBeSent{get;set;}
public List<SelectOption> getYear{get;set;}
public string strSMSBody{get;set;}
//To disable fields if data is not available
String session,statusOfLead,stringOfMobileNumbers;
public nmSendSMS()
{
objLead = new Lead();
leadYear ='';
defaultNumbersToBeAdded = '9820834921,9920726538';
messageToBeSent = '';
stringOfMobileNumbers= '';
}
//Method to send SMS
public PageReference SendSMS()
{
if(leadYear!='' || messageToBeSent!='')
{
session = objLead.nm_Session__c;
integer lengthOfCommaSeperatedNumbers;
String finalString ='';
statusOfLead = objLead.Status;
list<lead> leadNumbersList = [select MobilePhone from Lead where Status=:statusOfLead and nm_Session__c=:session and nm_Year__c=:integer.valueOf(leadYear)];
for(Lead obj :leadNumbersList)
{
stringOfMobileNumbers = obj.MobilePhone+','+stringOfMobileNumbers;
}
System.debug('stringOfMobileNumbers -->'+stringOfMobileNumbers);
lengthOfCommaSeperatedNumbers = stringOfMobileNumbers.length();
finalString = stringOfMobileNumbers.substring(0,lengthOfCommaSeperatedNumbers-1);
finalString = finalString + defaultNumbersToBeAdded;
System.debug('Final String--->'+finalString+'Message To Be Sent-->'+messageToBeSent);
String response = SMSSenderWebService.sendSMSForNotContactedLead(finalString,messageToBeSent);
System.debug('Response-->'+response);
}
else
{
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Warning,'Please Mention all the fields For Lead Search'));
return null;
}
return null;
}
public List<SelectOption> getYear()
{
List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('2016','2016'));
options.add(new SelectOption('2017','2017'));
options.add(new SelectOption('2018','2018'));
options.add(new SelectOption('2019','2019'));
return options;
}
}
Test Class:-
#isTest
public class nmSendSMSTracker
{
public static Lead obj;
public static nm_Centers__c objLearningCenter;
public static nm_Program__c program;
public static nm_EligiblityCriteria__c eligibility ;
static testMethod void tesMethod()
{
LoadData();
PageReference pg = new PageReference('/apex/nmSendSMS');
Test.setCurrentPage(pg);
Test.StartTest();
nmSendSMS smsSend = new nmSendSMS();
smsSend.getYear();
smsSend.objLead = obj;
smsSend.messageToBeSent ='Hello Vikas';
smsSend.SendSMS();
Test.StopTest();
}
static void LoadData()
{
nm_EscalationMatrix__c objCustomSeetings3 = new nm_EscalationMatrix__c();
objCustomSeetings3.name='0-1 Week';
objCustomSeetings3.nm_LCEscalationTime__c='22:45';
objCustomSeetings3.nm_RemidertoIC__c='22:45';
objCustomSeetings3.nm_HOEscalationTime__c='20:56';
objCustomSeetings3.nm_RemidertoHO__c='22:45';
insert objCustomSeetings3;
nm_EscalationMatrix__c objCustomSeetings = new nm_EscalationMatrix__c();
objCustomSeetings.name='2-4 Months';
objCustomSeetings.nm_LCEscalationTime__c='20:45';
objCustomSeetings.nm_RemidertoIC__c='21:45';
objCustomSeetings.nm_HOEscalationTime__c='20:56';
objCustomSeetings.nm_RemidertoHO__c='21:45';
insert objCustomSeetings;
nm_EscalationMatrix__c objCustomSeetings2 = new nm_EscalationMatrix__c();
objCustomSeetings2.name='3-6 Week';
objCustomSeetings2.nm_LCEscalationTime__c='20:34';
objCustomSeetings2.nm_RemidertoIC__c='21:45';
objCustomSeetings2.nm_HOEscalationTime__c='20:56';
objCustomSeetings2.nm_RemidertoHO__c='21:45';
insert objCustomSeetings2;
nm_Holidays__c objHoliday = new nm_Holidays__c();
objHoliday.Name='Holi';
objHoliday.nm_Date__c=system.today();
insert objHoliday;
// profile objprofile =[SELECT Id FROM Profile WHERE Name='System Administrator'];
user usr = [Select id from user limit 1];
SystemConfiguration__c objSystemConfiguration=new SystemConfiguration__c();
objSystemConfiguration.name='test';
objSystemConfiguration.nm_BusinessHoursStartTime__c='012213';
objSystemConfiguration.nm_BusinessHoursEndTime__c='0234533';
insert objSystemConfiguration;
Recordtype rt=[select id from Recordtype where sobjectType='nm_Centers__c' AND name ='Learning Center'];
objLearningCenter = new nm_Centers__c();
objLearningCenter.RecordTypeID =rt.id;
objLearningCenter.nm_CenterCode__c ='002';
objLearningCenter.nm_CenterCity__c='Delhi';
objLearningCenter.nm_City__c='Delhi';
objLearningCenter.nm_StateProvince__c='Delhi';
objLearningCenter.nm_Street__c='Laxmi Ngar';
objLearningCenter.nm_PostalCode__c='110091';
insert objLearningCenter;
program = new nm_Program__c();
program.nmIsActive__c = true;
program.nm_ProgramCode__c = 'test';
program.nm_ProgramDuration__c= 2.0;
program.nm_ProgramName__c = 'Post grad diploma finance';
program.nm_ProgramValidity__c = 4;
program.nm_TotalSemesters__c = 4;
program.nm_Type__c = 'Post Graduate Diploma Program';
insert program;
eligibility = new nm_EligiblityCriteria__c();
eligibility.Name = 'Bachelors degree';
eligibility.nm_EligiblityCriteria__c = 'bjhwbghbjgw';
eligibility.Experience_Required_In_Year__c= 2;
eligibility.Graduation_Percentage__c = 6;
eligibility.Graduation_Required__c = true;
insert eligibility;
obj = new Lead();
obj.Email='amit.kumar#saasfocus.com';
obj.MobilePhone='8377985721';
obj.FirstName='sandy';
obj.LastName='babar';
obj.nm_BloodGroup__c='B+';
obj.nm_Gender__c='male';
obj.nm_FathersName__c='subhash';
obj.nm_MothersName__c='kalpana';
obj.nm_StateProvince_P__c='maharashtra';
obj.nm_Nationality__c='Indian';
obj.nm_Street_P__c='xyz';
obj.nm_LocalityName__c='mohitep';
obj.nm_SelfLearningMaterial__c='Send to my shipping address';
obj.Status='Cold';
obj.nm_Session__c = 'January';
obj.nm_NameofBoard__c='CBSE';
obj.nm_EligiblityCriteria__c = eligibility.id;
obj.nm_Program__c = program.id;
obj.nm_InformationCenter__c =objLearningCenter.id;
obj.nm_10thPercentage__c=77.00;
obj.nm_NameofBoard__c='ICSC';
obj.nm_YearofCompletion__c='2000';
obj.nm_NameofSchool__c='nutan';
obj.nm_Class12OrDiploma__c='HSC';
obj.nm_NameofBoard12__c='LCSC';
obj.nm_YearofCompletion12__c='2002';
obj.nm_NameofSchool12__c='dfg';
obj.nm_Stream__c='adw';
obj.nm_BachelorsDegreeName__c='gfc';
obj.nm_Specialization__c='gf';
obj.nm_NameofUniversity__c='G K university';
obj.nm_BachelorsDegreePercentage__c=55.00;
obj.nm_GraduationDegreeMode__c='fgc';
obj.nm_YearofCollegeCompletion__c='2006';
obj.LeadSource='Web';
obj.OwnerId=usr.id;
insert obj;
}
}
Error Message:
System.TypeException: Invalid integer:
Class.nmSendSMS.SendSMS: line 37, column 1
Class.nmSendSMSTracker.tesMethod: line 19, column 1
List<Lead> leadNumbersList = [select MobilePhone from Lead where nm_Year__c=:leadYear];
Works for me and I get the correct Lead(s) in the list

Apex Test case for Email Class

I have following class to send email
global class SendConfirmation {
public SendConfirmation(ApexPages.StandardController controller)
{
}
Webservice static void SendEmail(string contactId,string oppId)
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(contactId);
mail.setWhatId(oppId);
mail.setTemplateId('00Xd0000000PFaY');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
ablove class is fine
but not able to get following test case to complete code coverage in eclipse
#isTest
private class SendConfirmationTestCase {
private static testMethod void myUnitTest() {
Contact con = new Contact();
con.FirstName = 'Anil';
con.LastName = 'Dutt';
con.Email = 'anil#swiftsetup.com';
insert con;
Opportunity oppNew = new Opportunity();
oppNew.Name = 'Test Opp';
oppNew.StageName = 'Ticketing';
oppNew.CloseDate = System.now().date();
insert oppNew;
//ApexPages.StandardController sc = new ApexPages.StandardController(con);
//SendConfirmation sc1=new SendConfirmation (sc);
//sc1.SendEmail();
}
}
If i comment out last 3 lines from test case
Following error is coming
SendConfirmationTestCase: Invalid type: SendConfirmation
Thanks in advance for your help..
Try this, it's testing at 100% for me.
global class SendConfirmation
{
public SendConfirmation(ApexPages.StandardController controller)
{
}
Webservice static void SendEmail(string contactId,string oppId)
{
Messaging.SingleEmailMessage mail
= new Messaging.SingleEmailMessage();
mail.setTargetObjectId(contactId);
mail.setWhatId(oppId);
// assuming this Template ID exists in your org
mail.setTemplateId('00Xd0000000PFaY');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
private static testMethod void myUnitTest()
{
Contact con = new Contact();
con.FirstName = 'Anil';
con.LastName = 'Dutt';
con.Email = 'anil#swiftsetup.com';
insert con;
Opportunity oppNew = new Opportunity();
oppNew.Name = 'Test Opp';
oppNew.StageName = 'Ticketing';
oppNew.CloseDate = System.now().date();
insert oppNew;
ApexPages.StandardController sc
= new ApexPages.StandardController(con);
SendConfirmation sc1=new SendConfirmation (sc); // test constructor
// Not: sc1.SendEmail();
// Because method is a webservice in a global class
SendConfirmation.SendEmail(con.Id,oppNew.Id);
}
}

Resources