How to write a test function for salesforce ConnectApi.FeedElement - salesforce

this is my code
public class ChatterFunction{
public ChatterFunction(){
LIST<ISSUE__C> issID = [SELECT Id, Name FROM ISSUE__C];
for(ISSUE__C i : issID){
postfeed(i.Id);
}
}
public static void postfeed(String iss){
ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();
messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
mentionSegmentInput.id = '00528045147FTed';
messageBodyInput.messageSegments.add(mentionSegmentInput);
textSegmentInput.text = 'Something';
messageBodyInput.messageSegments.add(textSegmentInput);
feedItemInput.body = messageBodyInput;
feedItemInput.feedElementType = ConnectApi.FeedElementType.FeedItem;
feedItemInput.subjectId = iss;
ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(null,feedItemInput );
}
}
and I tried to test it with code
#IsTest(SeeAllData=true) public static void testpostfeed() {
System.assertEquals(postfeed('a000l0013315hgr'),null);
}
but it shows the error message: Method does not exist or incorrect signature: postfeed(String)
I have no idea why it doesn't exist ....

Your method is static so you need to call it like this
System.assertEquals(ChatterFunction.postfeed('...'), null);

Related

How to improve the coverage of this test class in Apex?

I have created a test class with 51% code coverage till line no 34.
Further, I tried to satisfy if condition but I couldn't. Now I am not getting how to do with 100% code coverage.
Here is the Apex class:
public class AssignProjectController {
public String CaseIds;
public String status {get;set;}
public List<Project__c> activeProjects {get;set;}
public String keyWordSearched {get;set;}
public Id projectId {get;set;}
public AssignProjectController (){
CaseIds = ApexPages.currentPage().getParameters().get('id');
}
public void getProjects(){
status = '';
String searchQuery = 'FIND \'' + keyWordSearched + '*\' IN ALL FIELDS RETURNING Project__c (id,Name,Description__c where Status__c =\'Active\')';
try{
List<List<Project__c >> searchList = search.query(searchQuery);
activeProjects = searchList[0];
if(activeProjects.size() == 0) status = 'No search result found.';
}catch(Exception ex){
system.debug('ex..'+ex.getMessage());
}}}
public PageReference assignProjectToCases(){
List<Case__c> customSettingList = Case__c.getall().values();
List<String> settingRecordTypeList = new List<String>();
for(Case__c caseObj:customSettingList){
settingRecordTypeList.add(caseObj.Name);
}
List<RecordType> recordTypeListData = [SELECT Id FROM RecordType WHERE SObjectType = 'Case' and Name In : settingRecordTypeList];
if(CaseIds != null){
List<String> caseIDList = new List<String>();
caseIDList = CaseIds.split(',');
if([Select id from Case where Id In : caseIDList and RecordType.Id NOT In : recordTypeListData].size() > 0){
status = 'failed';
}else{
List<Case> cases = [Select id,Project__c,RecordType.Name from Case where Id In : caseIDList and RecordType.Id In : recordTypeListData];
if(cases.size() > 0){
for(case caseOb: cases){
caseOb.Project__c = projectId ;
}
try{
update cases ;
status = 'Changes are scheduled';
}catch(Exception ex){
system.debug('AssignProjectController :::'+ex.getMessage());
status = 'Something Went Wrong';
}}}}
return null;
}}
Here is the test class- which I tried to resolve
#isTest public class TestAssignProjectController {
public static Project__c insertProject(){
Project__c proObj = new Project__c();
proObj.Name = 'testProject';
proObj.Status__c = 'Active';
proObj.Description__c = 'for testing';
proObj.Internal_Email_Alias__c = 'a#test.com';
return proObj;
}
public static Account getAccount(){
Account accoObj = new Account();
accoObj.Name = 'testAcc';
accoObj.Location__c = 'testLocation';
accoObj.Type = 'CM';
accoObj.BillingCountry = 'United States';
return accoObj;
}
public static Contact insertContact(Account accObj){
Contact conObj = new Contact();
conObj.FirstName = 'test';
conObj.LastName = 'testLastname';
conObj.AccountId = accObj.Id;
conObj.Email = 'abc#gmail.com';
return conObj;
}
public static Id getTechTypeId(){
return Schema.SObjectType.Case.getRecordTypeInfosByName().get('Tech ').getRecordTypeId();
}
public static Case insertCase(String conId, String proId){
Case caseObj = new Case();
caseObj.Project__c = proId;
caseObj.ContactId = conId;
caseObj.Status = 'Open';
caseObj.Inquiry_Type__c = 'All';
caseObj.Subject = 'TestSubject';
caseObj.Description = 'TestDescription';
caseObj.Case_Is_Reopened__c = false;
caseObj.RecordTypeId = getTechTypeId();
return caseObj;
}
public static testmethod void testMethodExecution(){
AssignController asigncon = new AssignController ();
Project__c proObj = insertProject();
insert proObj;
System.assertEquals(proObj.Status__c,'Active');
Account accObj = getAccount();
insert accObj;
System.assertNotEquals(accObj.Id,null);
Contact conObj = insertContact(accObj);
insert conObj;
System.assertNotEquals(conObj.Id,null);
Case caseObj = insertCase(conObj.Id, proObj.Id);
insert caseObj;
system.debug(caseObj);
//Set baseURL & case ID
PageReference pageRef = Page.Assign;
pageRef.getParameters().put('id',caseObj.id+',');
AssignController asigncon1 = new AssignController ();
asigncon1.getProjects();
asigncon1.assignProjectToCases();
}}
If you are referring if(cases.size() > 0) this statement, then surely there is problem of inserting the case. Make sure that insert caseObj; is working and inserts data in Salesforce backend.
If there is no data in case object, the test method cannot cover the if statement.

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

How to test #future methods

I've the following services:
public with sharing class LibraryService {
public static void remove(String jsonString) {
Library__c library = [ SELECT Id, ilms__Library_Name__c FROM ilms__Library__c WHERE Id = libraryId ] ;
AccessService.deleteReviewerGroup(library);
delete library;
}
}
AccessService class
public with sharing class AccessService {
public static void deleteLibraryReviewerGroup(Library__c library) {
List<Library__Share> reviewersGroups = [ SELECT UserOrGroupId FROM ilms__Library__Share WHERE AccessLevel = 'Read' AND ParentId = :library.Id ];
System.debug('reviewersGroups: ' + reviewersGroups);
if(reviewersGroups.size() == 1) {
String reviewersGroupId = reviewersGroups[0].UserOrGroupId;
delete reviewersGroups;
AccessService.deleteReviewerGroup(reviewersGroupId);
}
return;
}
#future
public static void deleteReviewerGroup(String groupId) {
List<Group> reviewerGroup = [ SELECT Id FROM Group WHERE Id = :groupId ];
delete reviewerGroup;
}
}
Now, when I try to test the LibraryService remove method, I keep receiving the below error:
first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa).
#isTest(SeeAllData=true)
private class TestLibrary {
static testMethod void testRemoveLibrary() {
Library__c library = new Library__c(...);
Boolean isRemoved = LibraryService.remove(TestUtilsClass.idJson(library.Id));
System.assertEquals(isRemoved, true);
}
}
I tried adding Test.startTest() and Test.stopTest() to the testRemoveLibrary method, but I still get the same error. Am I doing something wrong? How do I fix this?
#isTest(SeeAllData=true)
private class TestLibrary {
static testMethod void testRemoveLibrary() {
Library__c library = new Library__c(...);
Test.start();
Boolean isRemoved = LibraryService.remove(TestUtilsClass.idJson(library.Id));
Test.stop();
System.assertEquals(isRemoved, true);
}
}
Please add Test.start and stop including your method.

Passing checkedlistbox.checked items cast as a List<BuiltInCategory> from a Form instance to a Revit class function

I am not having any issues making calls from the form instance to the Revit class. It's when I try to assign a List to the Revit class's function categoryList(), that I get a variable doesn't exist in the context error. I tried prefixing a reference to the instance of the form class "Form UF = new Form;" This doesn't work.
//The Revit Class
public Result Execute(ExternalCommandData commandData, ref string message,....)
{
User_Form UF = new User_Form(commandData);
UF.ShowDialog();
public List<BuiltInCategory> categoryList(Document doc, int intSwitch)
{
//list built in categories for built in filter_1
builtInCats_List = new List<BuiltInCategory>();
switch (intSwitch)
{
case (1):
...
case (3):
...
case (4):
{
builtInCats_List = newStateCb1;
return builtInCats_List;
}
default:
{
builtInCats_List = newStateCb1;
return builtInCats_List;
}
}
}
using Form = System.Windows.Forms.Form;
using WS = ModelAuditor_2014.WorksetSorter_2014;
using ModelAuditor_2014;
using System.Threading;
//The Form
namespace ModelAuditor_2014
{
public partial class User_Form : Form
{
//Constructor
WorksetSorter_2014 WS = new WorksetSorter_2014();
//Revit references
public Autodesk.Revit.UI.UIApplication rvtUiApp;
public Autodesk.Revit.UI.UIDocument rvtUiDoc;
public Autodesk.Revit.ApplicationServices.Application rvtApp;
//Global Variables
public List<BuiltInCategory> Filter01_CategoryList;
public List<BuiltInCategory> Filter02_CategoryList;
public int intSwitch;
public List<BuiltInCategory> newStateCb1;
public User_Form(ExternalCommandData commandData)
{
//Revit references
rvtUiApp = commandData.Application;
rvtUiDoc = rvtUiApp.ActiveUIDocument;
rvtApp = rvtUiApp.Application;
InitializeComponent();
}
public void User_Form_Load(object sender, EventArgs e)
{
//use rvtDoc = Doc
Autodesk.Revit.DB.Document rvtDoc = .....
//CheckedListBox for filter01
checkedListBox1.DataSource = WS.categoryList(rvtDoc, intSwitch = 1);
Filter01_CategoryList = new List<BuiltInCategory>();
Filter01_CategoryList = WS.RetrieveSchema(rvtDoc, false);
foreach (BuiltInCategory ChkedB1 in Filter01_CategoryList)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.Items[i].ToString() == ChkedB1.ToString())
{
checkedListBox1.SetItemChecked(i, true);
}
}
}
public List<BuiltInCategory> returnNewStateCB1()
{
newStateCb1 = checkedListBox1.CheckedItems.Cast
<BuiltInCategory>().ToList<BuiltInCategory>();
return newStateCb1;
}
I passed the list from the win form to another public function in the revit app, I was able to access the list returned by this function.

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