How to write an Apex Test Class for Importing a CSV File? - unit-testing

Hello! I am unable to test the written apex class.. Could you help me with this task?
Through the component, we transfer the ID of the CSV file sent to the server to the apex class, after which our apex class creates stations if there were none before, and also updates the list of sensors based on the records of the CSV file (insert/ update).
Controller Class
public inherited sharing class lwnReadCsvFileController {
#AuraEnabled
public static list<Sensor__c> readCSVFile(Id idContentDocument){
list<Sensor__c> lstSensToInsert = new list<Sensor__c>();
if(idContentDocument != null) {
// getting File Data based on document id
ContentVersion objVersion = [SELECT Id, VersionData FROM ContentVersion WHERE ContentDocumentId =:idContentDocument];
// split the file data
list<String> lstCSVLines = objVersion.VersionData.toString().split('\n');
//creating Basic Stations records
List<Base_Station__c> createdBSRec = [SELECT Name, Id From Base_Station__c];
List<Base_Station__c> newBSRec = new List<Base_Station__c>();
Set<String> uniqueSet = new Set<String>();
for ( Integer i = 1; i < lstCSVLines.size(); i++ ) {
integer coincidences = 0;
list<String> csvRowData = lstCSVLines[i].split(',');
for ( Base_Station__c rec : createdBSRec ) {
if (csvRowData[0] == rec.Name) {
coincidences++;
}
}
if ( coincidences == 0 ) {
uniqueSet.add(csvRowData[0]);
}
}
List<String> uniquelist = new List<String>(uniqueSet);
for (integer i = 0; i < uniquelist.size() ; i++) {
Base_Station__c newBS = new Base_Station__c(Name = uniquelist[i]);
NewBSRec.add(newBS);
}
upsert newBSRec;
//creating Sensor records
for(Integer i = 1; i < lstCSVLines.size(); i++){
Sensor__c objRec = new Sensor__c();
list<String> csvRowData = lstCSVLines[i].split(',');
string tempBase = csvRowData[0];
objRec.Name = csvRowData[1];
objRec.Base_Station__c = [SELECT Id From Base_Station__c Where Name = :tempBase ].id;
objRec.Sensor_ID__c = integer.valueof(csvRowData[1]);
objRec.Status__c = csvRowData[2];
objRec.Sensor_Model__c = csvRowData[3];
lstSensToInsert.add(objRec);
}
if(!lstSensToInsert.isEmpty()) {
List<Sensor__c> createdSenRec = [SELECT Name, Sensor_ID__c From Sensor__c];
for (Sensor__c sens : lstSensToInsert ) {
integer coincidences = 0;
for (Sensor__c rec : createdSenRec ) {
if (sens.Sensor_ID__c == rec.Sensor_ID__c) {
sens.id = rec.id;
update sens;
coincidences++;
}
}
if ( coincidences == 0 ) {
insert sens;
}
}
}
}
return lstSensToInsert;
}
}
Test Class 100% coverage
#isTest
public class IwnReadCsvFileControllerTest {
public static String str = 'BASE STATION,SENSOR ID,STATUS,SENSOR MODEL \n' +
'Leeds,1,Enabled ,R8 \n' +
'Glasgow Central,2,Enabled,R8';
#isTest
public static void testReadCSVFile(){
Base_Station__c newBS = new Base_Station__c(Name = 'Leeds');
upsert newBS;
Sensor__c newSensor = new Sensor__c (Name = '1', Sensor_Id__c = 1, Status__c = 'Enabled', Base_Station__c = newBs.id);
insert newSensor;
ContentVersion contentVersionInsert = new ContentVersion(
Title = 'Test',
PathOnClient = 'Test.csv',
VersionData = Blob.valueOf(str),
IsMajorVersion = true
);
insert contentVersionInsert;
Id getId = [Select ContentDocumentId From ContentVersion Where Id =:contentVersionInsert.id and isLatest=true].ContentDocumentId;
List<Sensor__c> result = lwnReadCsvFileController.readCSVFile(getId);
}
}

Your unit test class is passing a ContentVersion Id:
List<Sensor__c> result = lwnReadCsvFileController.readCSVFile(contentVersionInsert.Id);
but your class is treating this Id as a ContentDocument Id:
public static list<Sensor__c> readCSVFile(Id idContentDocument){
if(idContentDocument != null) {
ContentVersion objVersion = [
SELECT Id, VersionData
FROM ContentVersion
WHERE ContentDocumentId =:idContentDocument
];
Your test class needs to query for the ContentDocumentId of the newly-inserted ContentVersion and pass that Id into your class under test.

Related

Test Class not increasing the code coverage of trigger

I have created a trigger that converts products(Lineitems) to assets when opportunity moves to closed won stage. It is working fine on Sandbox but the problem is code coverage. When I'm writing a test class the method is passed but the code coverage of trigger is still 0%. Any help would be appreciated.
#Trigger
trigger OpportunityTrigger on Opportunity (after insert,after update) {
OpportunityTriggerHandler.testhandler(trigger.new); }
#Class
public Class OpportunityTriggerHandler {
public static Boolean isFirstTime = true;
public static void testhandler(List <Opportunity> oplist)
{
list <OpportunityLineItem> OLI=new list<OpportunityLineItem>();
list<Asset> ast = new list<Asset>();
for(Opportunity o: oplist) {
if(o.isWon == true && o.HasOpportunityLineItem == true && o.AccountId !=null)
{
String opptyId = o.Id;
OLI = [Select UnitPrice, Quantity , PricebookEntry.Product2Id, PricebookEntry.Product2.Name, Description From OpportunityLineItem where OpportunityId = :opptyId ];
Asset a = new Asset();
for(OpportunityLineItem ol: OLI){
List<Asset> ast1 = [Select Product2Id From Asset where Opportunity__c = :opptyId and Product2Id = : ol.PricebookEntry.Product2Id];
if(ast1 .size()>0){
string prdId = string.valueOf(ast1[0].Product2Id );
string oliId = ol.PricebookEntry.Product2Id;
if(prdId != oliId ){
a = new Asset();
a.AccountId = o.AccountId;
a.Product2Id = ol.PricebookEntry.Product2Id;
a.Quantity = ol.Quantity;
a.Price = ol.UnitPrice;
a.PurchaseDate = o.CloseDate;
a.Status = 'Purchased';
a.Description = ol.Description;
a.Name = ol.PricebookEntry.Product2.Name;
a.Opportunity__c = o.Id;
ast.add(a);
}
}
else{
a = new Asset();
a.AccountId = o.AccountId;
a.Product2Id = ol.PricebookEntry.Product2Id;
a.Quantity = ol.Quantity;
a.Price = ol.UnitPrice;
a.PurchaseDate = o.CloseDate;
a.Status = 'Purchased';
a.Description = ol.Description;
a.Name = ol.PricebookEntry.Product2.Name;
a.Opportunity__c = o.Id;
ast.add(a);
}
}
} } update OLI; insert ast; } }
#testClass
#isTest
public class TestOpportunityTrigger{
Static testmethod void TestOpportunityTrigger(){
Test.startTest();
list <Opportunity> Opty =new list<Opportunity>();
OpportunityTriggerHandler.testhandler(Opty);
Opportunity o = new Opportunity();
OpportunityLineItem ol = new OpportunityLineItem();
Asset a = new Asset();
if(o.isWon == true && o.HasOpportunityLineItem == true && o.AccountId !=null)
{
a = new Asset();
a.AccountId = o.AccountId;
a.Product2Id = ol.PricebookEntry.Product2Id;
a.Quantity = ol.Quantity;
a.Price = ol.UnitPrice;
a.PurchaseDate = o.CloseDate;
a.Status = 'Purchased';
a.Description = ol.Description;
a.Name = ol.PricebookEntry.Product2.Name;
a.Opportunity__c = o.Id;
try{ insert a; }
catch(exception e)
{ system.assert(False); }
Test.stopTest();
}
else{}
}}

How to write test class for salesforce email template

I'm struggling to write a test class for visualforce email template that I have created as per business requirements but I don't know who to cover "get' methods in the test class.. I spent long hours doing research on google unfortunately I haven't found anything helpful.
I tried many ways to cover 'get' method in test class like below
myClass cls = new myClass;
cls.getMethod();
cls.getProperty = 'test';
but it's giving me the error message "List index out of bounds: 0" because I'm calling another method in getter and that methods takes list of records
Controller Class:
public class JobChangesEmail_ComplianceTeam_Cls {
public string jobId {get; set;}
// public string jUrl{get; }
// public string clientUrl {get; }
// public string endclientUrl {get;}
public static list<job__c> jobs;
public JobChangesEmail_ComplianceTeam_Cls()
{
jobs = [select j.Id,j.name,j.other_location__c,j.account__c,j.account__r.id, j.account__r.name,j.Job_Start_Date__c,j.Job_End_Date__c,j.Job_Status__c,j.account__r.Spreadsheet_SOPs__c,
j.account__r.Facility_SOPs__c,j.End_Client__c,End_Client__r.id,j.End_Client__r.name,j.End_Client__r.Spreadsheet_SOPs__c, j.End_Client__r.Facility_SOPs__c from Job__c j where Id=:jobId];
system.debug('-------------------------------------jobId '+jobId);
}
public list<job__c> getjbs()
{
jobs = [select j.Id,j.name,j.other_location__c,j.account__c, j.account__r.name,j.Job_Start_Date__c,j.Job_End_Date__c,j.Job_Status__c,j.account__r.Spreadsheet_SOPs__c,
j.account__r.Facility_SOPs__c,j.End_Client__c,j.End_Client__r.name,j.End_Client__r.Spreadsheet_SOPs__c, j.End_Client__r.Facility_SOPs__c from Job__c j where Id=:jobId];
system.debug('-------------------------------------jobId '+jobId);
return jobs;
}
Public static string generatejobUrl(list<job__c> jobs)
{
string jurl = System.URL.getSalesforceBaseUrl().toExternalForm() + '/'+jobs[0].Id;
return jurl;
}
Public static string generateclientUrl(list<job__c> jobs)
{
string cUrl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].account__r.id;
return cUrl;
}
Public static string generateEndclientUrl(list<job__c> jobs)
{
string endCUrl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].end_client__r.id;
return endCUrl;
}
public String getjUrl()
{
string jbUrl;
list<job__c> jobs = [select Id,name from Job__c where Id=:jobId];
jbUrl= System.URL.getSalesforceBaseUrl().toExternalForm() + '/'+jobs[0].Id;
return jbUrl;
}
public string clientUrl
{
get { return generateclientUrl(jobs); }
}
public string endclientUrl
{
get { return generateEndclientUrl(jobs); }
}
}
Test class I have written so far:
#isTest(seeAllData= true)
Public class JobChangesEmail_ComplianceTeam_Cls_test {
#isTest
public static void createJob()
{
string clienturl;
string endClienturl;
string joburl;
list<job__c> jobs = new list<job__c>();
Account a = new account(name='ghghghg',type='Other', Account_Status__c='Active',phone='9090909090');
insert a;
Contact contact = new Contact(FirstName='John',LastName='Adams',email='test#gamil.com',phone='14243443', accountid = a.id);
insert contact;
// Opportunity o = [Select id, Name, CloseDate ,Location__c ,AccountId from opportunity limit 1];
Job__c job = new Job__c();
job.Name = 'NewJob'; // Set to match test record
job.X_KOL__c = false; // Set to match test record
job.DE_Job_Type__c = null; // Set to match test record
job.Job_Name_Subject__c = 'TestJob';
job.Job_Start_Date__c = Date.today();
job.End_Client__c = a.Id;
job.Other_Location__c = 'SOS'; // Set to match test record
job.PM__c = 'Amber Anderson';
job.Booked_By__c = UserInfo.getUserId();
job.Account_Manager_COE__c = UserInfo.getUserId();
job.Account__c = a.Id;
job.Contact__c = contact.Id;
job.Respondent_Type__c = 'Acne';
job.Job_Status__c = 'Tentative';
job.Job_Qualification__c = 'Qualitative';
job.Recruitment_Method__c = 'Client List';
job.On_Site_Recruits__c = 5;
job.Off_Site_Recruits__c = 5;
job.London_Project_Number__c = 'Valyria';
job.Recruiting_Begin_Date__c = Date.today();
jobs.add(job);
if(jobs.size()>0)
{
insert jobs;
}
test.startTest();
clienturl = JobChangesEmail_ComplianceTeam_Cls.generateclientUrl(jobs);
endClienturl = JobChangesEmail_ComplianceTeam_Cls.generateEndclientUrl(jobs);
joburl = JobChangesEmail_ComplianceTeam_Cls.generatejobUrl(jobs);
Test.stopTest();
string cUrl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].account__r.id;
string Eurl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].end_client__r.id;
string jUrl = System.URL.getSalesforceBaseUrl().toExternalForm() + '/'+jobs[0].Id;
system.assertEquals(clienturl, cUrl);
system.assertEquals(endClienturl, Eurl);
system.assertEquals(joburl, jUrl);
JobChangesEmail_ComplianceTeam_Cls cls = new JobChangesEmail_ComplianceTeam_Cls();
cls.getjbs();
string id = cls.jobId;
id = [select id from job__c limit 1].id;
system.assertNotEquals(id,job.id);
}
}
above test class is not covering get methods or properties

test class for handler trigger is not covered

I did a trigger on content version ,but my handler class is not covered ,can you please explain to me why ?
please find below the code and screenshots for non covered lines
in my test class ,i created all data needed for the handler class i call the method with content version input
Trigger:
trigger contentversiontrigger on ContentVersion (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
if(trigger.isAfter && trigger.isInsert) {
Bytel_ContentVersionTriggerHandler.AlignAttachementsWithOpportunity(Trigger.New);
}
}
Trigger Handler
public with sharing class Bytel_ContentVersionTriggerHandler extends TriggerHandler {
public static void AlignAttachementsWithOpportunity(List<ContentVersion> contentVersion) {
Set<Id> contentDocumentIdSet = new Set<Id>();
String Contractid;
String Opportunityid;
for (ContentVersion cv : contentVersion) {
if(cv.ContentDocumentId != null)
{
contentDocumentIdSet.add(cv.ContentDocumentId);
}
}
list<ContentDocumentLink> cdl = [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet];
id LinkedEntityId =cdl[0].LinkedEntityId ;
// List<Contract> contractList = [SELECT Id, name FROM Contract where Id =:cdl.LinkedEntityId];
list<contract> Contracts = [SELECT Id, name FROM Contract where Id =:LinkedEntityId ];
if (!Contracts.isEmpty())
{
Contractid=Contracts[0].Id;
}
// Id Contractid = [SELECT Id, name FROM Contract where Id ='8005t0000001UQFAA2' limit 1].Id;
system.debug('test trigger' +Contractid) ;
// String Contractid= String.valueof(contractList[0].Id);
system.debug('ContractId' +Contractid) ;
list<Contract> contractssecond=[SELECT id ,vlocity_cmt__OpportunityId__c FROM Contract WHERE id =:Contractid limit 1];
if (!contractssecond.isEmpty())
{
Opportunityid=contractssecond[0].vlocity_cmt__OpportunityId__c;
}
system.debug('Opportunityid' +Opportunityid) ;
Id conDoc = cdl[0].ContentDocumentId;
//if (Opportunityid!=Null & conDoc!=Null) {
if (Opportunityid!=Null ) {
//create ContentDocumentLink record
ContentDocumentLink conDocLink = New ContentDocumentLink();
conDocLink.LinkedEntityId = Opportunityid;
conDocLink.ContentDocumentId = conDoc; //ContentDocumentId Id from ContentVersion
conDocLink.shareType = 'V';
insert conDocLink;
}
}
}
Test class of handler
#isTest
public class Bytel_ContentVersionTriggerHandlerTest {
static testMethod void createattachememtns() {
insert Bytel_TestDataFactory.createByPassSettings(false); // Custom setting bypass profile
insert Bytel_TestDataFactory.createGlobalVariableSettings(); // Custom setting globalVaribale, parameter callout end-point
insert Bytel_TestDataFactory.createOpportunityRaisonEchecSettings();
insert Bytel_TestDataFactory.createOpportunityStatusSettings();
Account acc = new Account(
Name = 'Test Account',
TypeIdentifiant__c = 'SIREN',
SIREN__c = '123765982',
Statut__c = 'Prospect'
);
insert acc;
Opportunity opp = Bytel_TestDataFactory.createOpportunity(
'FILL AUTO',
'Etape10',
acc.Id,
null
);
opp.Tech_AccountIdToDelete__c = acc.id;
opp.ScoringFinancier__c = 'Vert';
opp.siren__c = '123765981';
insert opp;
Quote quote = new Quote(Name = 'devis1', OpportunityId = opp.Id);
insert quote;
Contract contract1 = new Contract(
vlocity_cmt__QuoteId__c = quote.Id,
vlocity_cmt__OpportunityId__c=opp.id,
AccountId = acc.id
);
insert contract1;
Contract contract2 = new Contract(
vlocity_cmt__QuoteId__c = quote.Id,
AccountId = acc.id,
vlocity_cmt__OpportunityId__c=opp.id
);
insert contract2;
Blob bodyBlob=Blob.valueOf('Unit Test ContentVersion Body to be insert in test class for testing the');
ContentVersion contentVersion_1 = new ContentVersion(
Title='SampleTitle',
PathOnClient ='SampleTitle.txt',
Type_de_Fichier__c='RIB',
VersionData = bodyBlob,
origin = 'H'
);
insert contentVersion_1;
Contract contra = [SELECT Id
FROM Contract WHERE Id = :contract1.Id LIMIT 1];
List<ContentVersion> contentVersion_2 = [SELECT Id, Title, ContentDocumentId
FROM ContentVersion WHERE Id = :contentVersion_1.Id ];
// ContentDocumentLink contentlink = new ContentDocumentLink();
// contentlink.LinkedEntityId = contra.id;
// contentlink.contentdocumentid = contentVersion_2.contentdocumentid;
// contentlink.ShareType = 'V';
// insert contentlink;
Bytel_ContentVersionTriggerHandler.AlignAttachementsWithOpportunity(contentVersion_2);
}
}
After a first look, I guess you forgot to add #isTest to your test method.
#isTest
static testMethod void createattachememtns() {
//Your Code
}

How to edit a list of object c# linq to xml

<Team Side="Home" TeamRef="ref123">
<Goal PlayerRef="p1111" Time="10" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p4444" Time="11" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="13" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="17" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
</Team>
public void GetScorer(string side, string OCompetition, string OSeason, string OGameId)
{
try
{
var xDoc = XDocument.Load(test);
var query = from q in xDoc.Descendants("Team")
where (string)q.Attribute("Side") == side
from d in q.Elements("Goal")
select new
{
TeamRef = q.Attribute("TeamRef").Value,
PlayerRef = d.Attribute("PlayerRef").Value,
Time = d.Attribute("Time").Value
};
var count = 0;
foreach (var qq in query)
{
if (side == "Home")
{
if (HomeSlateScorerList[count].PlayerRef != qq.PlayerRef)
{
HomeSlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OSeason, OCompetition, OGameId) });
}
else
{
HomeSlateScorerList[count].Time = HomeSlateScorerList[count].Time + "' ";
}
}
if (side == "Away")
{
AwaySlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OCompetition, OSeason, OGameId) });
}
count++;
}
}
catch (Exception)
{
// ignored
}
}
I would like to edit a player in a list of players
HomeSlateScorerList = new List<Scorer>();
AwaySlateScorerList = new List<Scorer>();
what I would like to achieve is for e.g. there are two players with the ref of "p7777" so in the list of object I would like to have one player with the playerref of "p7777" so if the player exist the format will be
playerref = "p7777"
Time = 13' 17'
or if one player its
Time = 13'
or if another goal is added to the xml its
Time = 13' 17' 25'
HomeSlateScorerList = HomeSlateScorerList
.GroupBy(s => s.PlayerRef)
.Select(g => new Scorer { PlayerRef = g.Key, Time = string.Join(", ", g.Select(v => v.Time)) })
.ToList();
Thanks to: #SergeyS SergeyS

model item passed into dictionary is of type 'system.Collections.Generic.List'1[System.String]',but dictionary is model B

I am trying to create a create combobox with performcallback, but I got the error. here this error "the model item passed into dictionary is of type 'system.Collections.Generic.Lost'1[System.String]', but this dix=ctionary requires a model item of type 'DIS_iDealer.Models.SalesMonitoringModel'"
I don't know which code exactly I need to paste but this is what I have:
view combobox :
#model DIS_iDealer.Models.SalesMonitoringModel
#Html.DevExpress().ComboBoxFor(m => m.mpmGroupLine.DESCRIPTION, settings =>
{
settings.Name = "Desc_ID_CB";
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
settings.CallbackRouteValues = new { Controller = "Report", Action = "cbPartialCategoryDetail" };
settings.Properties.CallbackPageSize = 50;
settings.Properties.ValueField = "DESCRIPTION";
settings.Properties.TextField = "DESCRIPTION";
settings.Width = 150;
settings.SelectedIndex = 0;
settings.Properties.ClientSideEvents.BeginCallback = "function(s,e){e.customArgs['group_Id'] = Category_Id_CB.GetValue()}";
settings.Properties.ValidationSettings.ErrorTextPosition = ErrorTextPosition.Right;
settings.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithText;
settings.Properties.ValidationSettings.Display = Display.Dynamic;
}).BindList((List<string>)new DIS_iDealer.DataAccess.SalesMonitoringDAC().GetProductGroupDetail(Model.mpmGroupLine.GROUPID).ToList()).GetHtml()
controller :
namespace DIS_iDealer.Controllers
{
public class ReportController : BaseController
{
[HttpGet]
public ActionResult Report_SalesMonitoring_2()
{
SalesMonitoringModel mode = new SalesMonitoringModel();
//MPMPRODUCTGROUPLINE itemB = new MPMPRODUCTGROUPLINE();
/*List<string> mpmCate = mode.GetProductGroup();
if (mpmCate != null)
{
itemB.DESCRIPTION = mode.mpmGroupLine.DESCRIPTION;
}*/
ReportModels modelReport = new ReportModels();
if (TempData["ReportSalesMonitoring2"] != null)
{
modelReport = (ReportModels)TempData["ReportSalesMonitoring2"];
string reportParam = string.Empty;
foreach (string item in modelReport.ParameterReport)
{
reportParam += item;
}
ViewBag.IframeURL = modelReport.WebURL + reportParam;
}
return View(mode);
}
[ValidateInput(false)]
public ActionResult cbPartialCategoryDetail(string group_Id)
{
//SalesMonitoringModel model = new SalesMonitoringModel();
SalesMonitoringDAC model = new SalesMonitoringDAC();
List<string> itemDetail = model.GetProductGroupDetail(group_Id);
return PartialView("_cbPartialCategoryDetail", itemDetail);
}
}
}
Please let me know if you need more info. Thanks.