You need to sign in to do that
Don't have an account?
Unable to get coverage when facing errors because of other class and Trigger.
Stack Trace:: Class.SharingUtilityTest.testSetup: line 90, column 1
Error:: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AgentMapping: execution of BeforeInsert
caused by: System.QueryException: unexpected token: 'in'
Class.AgentMappingTriggerHandlerException.beforeInsert: line 50, column 1
Trigger.AgentMapping: line 15, column 1: [ ]
---Method from AgentMappingTriggerHandlerException line 50---
public static void beforeInsert(List<FI_Agent_Mapping__c> AgentMappingList){
List<String> useridList = new List<String>();
List<Id> pincodeList = new List<Id>();
for(FI_Agent_Mapping__c obj : AgentMappingList){
useridList.add(String.valueOf(obj.get('Fi_Agent__c')));
pincodeList.add(obj.PinCode__c);
}
String agentmappingquery='select id,Pincode_Map__c,Fi_Agent__c from FI_Agent_Mapping__c where in: pincodeList AND Fi_Agent__c IN:useridList';
//line 50--> List<FI_Agent_Mapping__c> targetobj=Database.query(agentmappingquery);
if(targetobj.size() > 0){
AgentMappingList.get(0).addError( 'User Has already Mapped to the same pincode');
}
}
---Trigger---
trigger AgentMapping on FI_Agent_Mapping__c (after insert, after update,before insert, before update) {
if(Trigger.isBefore && Trigger.IsUpdate){
AgentMappingTriggerHandlerException.beforeUpdate(Trigger.OldMap, Trigger.NewMap, Trigger.New);
}
if (Trigger.isAfter && Trigger.IsInsert) {
AgentMappingTriggerHandlerException.afterInsert(Trigger.OldMap, Trigger.NewMap, Trigger.New);
}
if(Trigger.IsAfter && Trigger.IsUpdate){
AgentMappingTriggerHandlerException.afterUpdate(Trigger.OldMap, Trigger.NewMap, Trigger.New);
}
if(Trigger.IsBefore && Trigger.IsInsert){
AgentMappingTriggerHandlerException.beforeInsert(Trigger.New);
}
}
----Main Test Class----
public without sharing class SharingUtility {
public static void recalculateSharing(String ObjectAPIName, Map<Id,String> sObjectIdVsStage, Map<Id,sObject> sObjectMap) {
List<sObject> sharingList = new List<sObject>();
List<Record_Access__mdt> recordAccessMeta = new List<Record_Access__mdt>();
map<Id, Sobject> shareMap = new Map<Id, Sobject>();
recordAccessMeta = [SELECT MasterLabel, rowCause__c, userField__c, access__c FROM Record_Access__mdt WHERE MasterLabel IN: sObjectIdVsStage.values() AND Object_API_Name__c =:ObjectAPIName];
for(Id loanid : sObjectIdVsStage.keyset()) {
for(Record_Access__mdt mdt: recordAccessMeta) {
if(mdt.MasterLabel.equalsIgnoreCase(sObjectIdVsStage.get(loanid)) && sObjectMap.get(loanid).get(mdt.userField__c)!=null ){
System.debug('in If');
String userid = mdt.userField__c;
sharingList.add(getLoanShareRecord(loanid,string.valueof(sObjectMap.get(loanid).get(userid)),mdt.access__c,mdt.rowCause__c));
shareMap.putall(sharingList); //when same cpa agent do D1 and D2 duplicate record is getting added in list so make it unique adding in map
}
}
}
List<Database.upsertResult> srList = Database.upsert(shareMap.values(), true);
for(Database.upsertResult dr : srList) {
if (dr.isSuccess()) {
System.debug('Successfully account with ID: ' + dr.getId());
}
else {
for(Database.Error err : dr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' + err.getFields());
}
}
}
}
public static void shareCaseRecordwithAgent (String sobj,Map<String,String> usercaseMap,String access, String reason){
caseShareRecordBulk(sobj, usercaseMap, access, reason);
}
public static sObject getLoanShareRecord (String parentId, String userId, String access, String reason){
String sObjectName = Id.valueOf(parentId).getSObjectType().getDescribe().getName();
System.debug('sObjectName:: '+sObjectName);
if(sObjectName.endsWithIgnoreCase('__c')) {
system.debug('sObjectName:'+sObjectName);
sObjectName = sObjectName.removeEnd('__c')+'__Share';
sObject obj = Schema.getGlobalDescribe().get(sObjectName).newSObject();
obj.put('AccessLevel', access != null ?access : 'Read');
obj.put('ParentId', parentId);
obj.put('UserOrGroupId', userId);
obj.put('rowCause', 'reason');//
return obj;
}
else if(sObjectName.equalsIgnorecase('Account')) {
sObjectName = 'AccountShare';
sObject obj = accountShareRecord(sObjectName,parentId,userId,access,reason);
return obj;
}else if(sObjectName.equalsIgnorecase('DocumentChecklistItem')) {
sObjectName = 'DocumentChecklistItemShare';
sObject obj = docCheckItemShareRecord(sObjectName,parentId,userId,access,reason);
return obj;
} else if(sObjectName.equalsIgnorecase('Case')) {
sObjectName = 'CaseShare';
sObject obj =caseShareRecord(sObjectName,parentId,userId,access,reason);
return obj;
} else if(sObjectName.equalsIgnorecase('Opportunity')) {
sObject obj = opportunityTeamRecord(sObjectName,parentId,userId,access,reason);
System.debug('Opportunity Share:: '+obj);
return obj;
}else{
system.debug('inside else:'+sObjectName);
return null;
}
}
@testvisible
private static sObject opportunityTeamRecord(String sobj,String parentId, String userId, String access, String reason){
if(userId.startsWith('005')){
OpportunityTeamMember oldTeamMemberRec = getPrevCreatedOppShare(parentId, userId);
OpportunityTeamMember oppTeamMember = new OpportunityTeamMember();
if(oldTeamMemberRec != null){
oppTeamMember.Id = oldTeamMemberRec.Id;
oppTeamMember.OpportunityAccessLevel = access;
}else{
oppTeamMember.OpportunityId = parentId;
oppTeamMember.UserId = userId;
oppTeamMember.OpportunityAccessLevel = access;
oppTeamMember.TeamMemberRole ='Team Member';
}
System.debug('oppTeamMember:: '+oppTeamMember);
return oppTeamMember;
}else{
return opportunityShareRecord(sobj, parentId, userId, access, reason);
}
}
@testvisible
private static OpportunityTeamMember getPrevCreatedOppShare(string parentId, string userId){
try{
OpportunityTeamMember oppTeamMember = [SELECT Id FROM OpportunityTeamMember WHERE OpportunityId=:parentId AND UserId=:userId Limit 1];
if(oppTeamMember != null){
return oppTeamMember;
}else{
return null;
}
}catch(Exception e){
return null;
}
}
@testvisible
private static sObject opportunityShareRecord(String sobj,String parentId, String userId, String access, String reason){
OpportunityShare oppShare = new OpportunityShare(OpportunityAccessLevel=access, OpportunityId = parentId, UserOrGroupId = userId);
return oppShare;
}
@testvisible
private static sObject accountShareRecord (String sobj,String parentId, String userId, String access, String reason){
sObject obj = Schema.getGlobalDescribe().get(sobj).newSObject();
obj.put('AccountAccessLevel', access != null ?access : 'Read');
obj.put('OpportunityAccessLevel','Read');
//obj.put('AccountAccessLevel', access != null ?access : 'Read');
obj.put('AccountId', parentId);
obj.put('UserOrGroupId', userId);
// obj.put('rowCause', reason);
return obj;
}
@testvisible
private static void removeAccess (Set<Id> parentId){
// delete all the existing sharing of these loan applications
System.debug('In removeAccess');
list<OpportunityShare> loanShareRecords = new list<OpportunityShare>();
loanShareRecords = [SELECT Id FROM OpportunityShare WHERE OpportunityId in :parentId];
Database.DeleteResult[] drList = Database.delete(loanShareRecords, false);
}
@testvisible
private static sObject docCheckItemShareRecord (String sobj,String parentId, String userId, String access, String reason){
sObject obj = Schema.getGlobalDescribe().get(sobj).newSObject();
obj.put('AccessLevel', access != null ?access : 'Read');
obj.put('ParentId', parentId);
obj.put('UserOrGroupId', userId);
return obj;
}
@testvisible
private static sObject caseShareRecord (String sobj,String parentId, String userId, String access, String reason){
String query = 'select id from CaseShare where UserOrGroupId =: userId and CaseId =: parentId';
List<SObject> targetObjRecords = Database.query(query);
delete targetObjRecords;
CaseShare obj = new CaseShare(CaseAccessLevel = access ,CaseId = parentId, UserOrGroupId = userId, RowCause = reason);
return obj;
}
@testvisible
private static void caseShareRecordBulk (String sobj,Map<String,String> parentId,String access, String reason){
List<Sobject> caseshareList= new List<Sobject>();
List<String> userIdList=parentId.values();
Set<String> CaseIdList=parentId.keySet();
String query = 'select id from CaseShare where UserOrGroupId in: userIdList and CaseId in: CaseIdList';
List<SObject> targetObjRecords = Database.query(query);
if(targetObjRecords.size() > 0){
delete targetObjRecords;
}else{
sendNotification(parentId);
}
for (String key : parentId.keySet()) {
Sobject sObjec = Schema.getGlobalDescribe().get('CaseShare').newSobject();
sObjec.put('CaseAccessLevel',access);
sObjec.put('CaseId',key);
sObjec.put('UserOrGroupId',parentId.get(key));
sObjec.put('RowCause',reason);
caseshareList.add(sObjec);
}
insert caseshareList;
}
@testvisible
public static void agentMappingShareRecord(Map<String,String> parentId,String access, String reason){
List<Sobject> caseshareList= new List<Sobject>();
Set<String> userIdList=parentId.keySet();
List<String> CaseIdList=parentId.values();
String query = 'select id from FI_Agent_Mapping__Share where UserOrGroupId in: userIdList and ParentId in: CaseIdList';
List<SObject> targetObjRecords = Database.query(query);
delete targetObjRecords;
for (String key : parentId.keySet()) {
Sobject sObjec = Schema.getGlobalDescribe().get('FI_Agent_Mapping__Share').newSobject();
sObjec.put('AccessLevel',access);
sObjec.put('ParentId',key);
sObjec.put('UserOrGroupId',parentId.get(key));
sObjec.put('RowCause',reason);
caseshareList.add(sObjec);
}
insert caseshareList;
}
public static void setDefaultOwner(List<Loan_Application_Actors__c> loanApplicationActorsList){
insert loanApplicationActorsList;
}
@testvisible
public static void removeAccess(Map<String,String> parentId){
List<String> userIdList=parentId.values();
Set<String> CaseIdList=parentId.keySet();
String query = 'select id,UserOrGroupId,CaseAccessLevel,CaseId from CaseShare where UserOrGroupId in: userIdList and CaseId in: CaseIdList';
List<sObject> targetObjRecords = Database.query(query);
if(targetObjRecords.size() > 0){
delete targetObjRecords;
}
}
public static void sendNotification(Map<String,String> caseuser){
Id typeId = [SELECT Id FROM CUstomNotificationType WHERE DeveloperName = 'FI_Agent_Notification'].Id;
for (String key : caseuser.keySet()) {
Messaging.CustomNotification notification = new Messaging.CustomNotification();
notification.setBody('FI Case Has Been Assigned To You');
notification.setTitle('FI Case Has Been Assigned To You');
notification.setSenderId(Userinfo.getUserId());
notification.setNotificationTypeId(typeId );
notification.setTargetId(key); // target object id
notification.send(new Set<String> { caseuser.get(key) }); // target user id.
}
}
public static List<Case> getCasesToShare(Set<Id> loanAppIdSet){
return [SELECT Id, Loan_Application__c FROM Case WHERE Loan_Application__c IN: loanAppIdSet];
}
public static void tvrCasesValidation(map<Id, Opportunity> lstCPAReviewApplications, map<Id, Opportunity>newMap){
if(lstCPAReviewApplications.size() > 0){
List<AggregateResult> lstAggrReult = [SELECT COUNT(Id) cnt, Loan_Application__c FROM Case WHERE Loan_Application__c IN: lstCPAReviewApplications.KeySet() AND Type Like 'TVR%' GROUP BY Loan_Application__c];
System.debug('lstAggrReult:: '+lstAggrReult);
if(lstAggrReult.size() > 0){
for(AggregateResult aggrResult : lstAggrReult){
String oppId = String.ValueOf(aggrResult.get('Loan_Application__c'));
Opportunity loanApplication = newMap.get(oppId);
System.debug('aggrResult:: '+aggrResult);
if(Integer.ValueOf(aggrResult.get('cnt')) < 2){
loanApplication.addError('Before Submitting to CPA Review, it is must to raise TVR CPV');
}
}
}else{
newMap.values()[0].addError('Before Submitting to CPA Review, it is must to raise TVR CPV');
}
}
}
}
:::::This is the test class facing above error:::::
@isTest
public class SharingUtilityTest {
@testSetup
public static void testSetup()
{
Account acc = new Account();
acc.Name = 'Central Team';
insert acc;
Contact objContact = new Contact(Salutation='Mr',LastName ='testCon',FirstName='fname',
AccountId = acc.Id,Email='ab.cd@efgh.com');
insert objContact;
Profile profileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
User usr = new User(LastName = 'test name',
FirstName='sample test',
Alias = 'jl test',
Email = 'test.sample@test.com',
Username = 'test.sample@test.com',
ProfileId = profileId.id,
LanguageLocaleKey = 'en_US',
timezonesidkey='Asia/Kolkata',
EmailEncodingKey = 'UTF-8',
LocaleSidKey = 'en_US',
IsActive = TRUE
);
Profile profileId1 = [SELECT Id FROM Profile WHERE Name = 'Credit Manager' LIMIT 1];
User usr1 = new User(LastName = 'test name',
FirstName='samplee test',
Alias = 'jl test',
Email = 'test.samplee@asdfcome.com',
Username = 'test.samplee@abcsdfcome.com',
ProfileId = profileId1.id,
LanguageLocaleKey = 'en_US',
timezonesidkey='Asia/Kolkata',
EmailEncodingKey = 'UTF-8',
LocaleSidKey = 'en_US',
// Contactid=objContact.id,
IsActive = TRUE
);
Group grp = new Group();
grp.Name ='BANRAD FINSERV';
grp.Type = 'Regular';
Insert grp;
insert usr ;
insert usr1;
system.runAs(usr) {
Case cas = new Case();
cas.AccountId=acc.id;
cas.Origin='Draft';
cas.SuppliedEmail='xyz@gmail.com';
insert cas;
opportunity opp= new opportunity();
opp.AccountId=acc.Id;
opp.Name='abc';
opp.StageName='closed won';
opp.CloseDate=date.today();
insert opp;
Loan_Application_Actors__c loan= new Loan_Application_Actors__c();
loan.name='application';
insert loan;
CaseShare ca= new CaseShare();
ca.CaseAccessLevel='Read';
ca.RowCause='Manual';
ca.UserOrGroupId=usr.id;
ca.CaseId=cas.id;
Database.SaveResult sr=Database.insert(ca,false);
opportunityTeamMember oppme= new opportunityTeamMember();
oppme.OpportunityId=opp.id;
oppme.UserId=usr.id;
insert oppme;
FI_Agent_Mapping__C fi= new FI_Agent_Mapping__c();
fi.Fi_Agent__c=usr.Id;
fi.Name ='A R ASSOCIATES';
fi.Fi_Agent__c = usr1.Id;
insert fi;
FI_Agent_Mapping__Share ag= new FI_Agent_Mapping__Share();
ag.AccessLevel='Read';
ag.RowCause='Manual';
ag.UserOrGroupId=usr.id;
ag.ParentId=fi.Id;
Database.SaveResult sr1=Database.insert(ag,false);
}
}
public static testmethod void shareCaseRecordwithAgentTest(){
case cas= [select id,origin from case limit 1];
user usr = [select id from user where IsActive = TRUE and Profile.name = 'System Administrator' limit 1];
user usr1 = [select id from user where IsActive = TRUE and Profile.name = 'Credit Manager' limit 1];
CUstomNotificationType cu=[select DeveloperName from CUstomNotificationType where DeveloperName='FI_Agent_Notification' LIMIT 1];
Account acc=[Select id from Account limit 1];
opportunity opp=[select name from opportunity LIMIT 1];
Loan_Application_Actors__c loan=[select name from Loan_Application_Actors__c LIMIT 1];
opportunityTeamMember oppme=[select id,opportunityid from opportunityTeamMember limit 1];
caseshare casesh=[select id from caseshare Limit 1];
FI_Agent_Mapping__C agent=[select id from FI_Agent_Mapping__C Limit 1];
FI_Agent_Mapping__Share agentShare=[select id from FI_Agent_Mapping__Share Limit 1];
List<Loan_Application_Actors__c> loanList = new List<Loan_Application_Actors__c>();
for(integer i=0;i<3;i++){
Loan_Application_Actors__c lo= new Loan_Application_Actors__c();
lo.Name='aaa';
loanList.add(lo);
}
system.runAs(usr){
set<id> sid= new set<id>();
string soobj = '';
Map<String,String> usercaseMap = new Map<String,String>();
usercaseMap.put(String.valueOf(cas.id),String.valueOf(usr1.id));
Map<id,sObject> caseMap = new Map<id,sObject>();
caseMap.put(cas.id,cas);
Map<id,string> caseMap1 = new Map<id,string>();
caseMap1.put(cas.id,cas.Origin);
Map<String,String> userAgentMap = new Map<String,String>();
userAgentMap.put(String.valueOf(agent.id),String.valueOf(usr.id));
SharingUtility.setDefaultOwner(loanList);
SharingUtility share = new SharingUtility();
SharingUtility.shareCaseRecordwithAgent('case',usercaseMap,'Read','manual');
string sobj ='Case';
SharingUtility.caseShareRecord(soobj,cas.Id,usr1.Id,'Read','manual');
string sobjAcc ='AccountShare';
SharingUtility.accountShareRecord(sobjAcc,acc.id,usr1.Id,'Read','manual');
string sobjitem ='DocumentChecklistItemShare';
SharingUtility.getLoanShareRecord(loan.Id,usr1.Id,'Read','manual');
SharingUtility.getLoanShareRecord(cas.Id,usr1.Id,'Read','manual');
SharingUtility.getLoanShareRecord(acc.Id,usr1.Id,'Read','manual');
SharingUtility.getLoanShareRecord(opp.id,usr1.Id,'Read','manual');
SharingUtility.removeAccess(sid);
SharingUtility.removeAccess(usercaseMap);
SharingUtility.opportunityShareRecord('OpportunityShare',opp.Id,usr.Id,'Read','manual');
SharingUtility.recalculateSharing('Case',caseMap1,caseMap);
SharingUtility.agentMappingShareRecord(userAgentMap,'Read','manual');
}
}
}