Test coverage for test class of trigger is showing 53 constantly - triggers

I am new to salesforce development.I have written test class for following trigger, which is having coverage as 53 only. I tried several times by adding and changing code lines into test class but it is still showing 53. Could you please help me to resolve this?
Thanks in advance. any help would be appreciated.
trigger CaseTrigger on Case (before insert,before update, after update)
{
if((Trigger.isBefore && Trigger.isUpdate)||(Trigger.isBefore && Trigger.isInsert))
{
List<Id> contactIds = new List<Id>();
List<Id> acctIds = new List<Id>();
for (Case c: Trigger.new){
if (c.EntitlementId == null && c.ContactId!= null && c.AccountId!= null){
contactIds.add(c.ContactId);
acctIds.add(c.AccountId);
}
}
if(contactIds.isEmpty()==false || acctIds.isEmpty()==false){
/* Added check for active entitlement */
List <EntitlementContact> entlContacts = [Select e.EntitlementId,e.ContactId,e.Entitlement.AssetId From EntitlementContact e
Where e.ContactId in:contactIds
And e.Entitlement.EndDate >= Today And e.Entitlement.StartDate <= Today];
if(entlContacts.isEmpty()==false){
for(Case c: Trigger.new){
if(c.EntitlementId == null && c.ContactId!= null){
for(EntitlementContact ec:entlContacts){
if(ec.ContactId==c.ContactId){
c.EntitlementId = ec.EntitlementId;
if(c.AssetId==null && ec.Entitlement.AssetId!=null)
c.AssetId=ec.Entitlement.AssetId;
break;
}
} // end for entitlement
}
} // end for case
} else{
List <Entitlement> entls = [Select e.StartDate, e.Id, e.EndDate, e.AccountId, e.AssetId
From Entitlement e
Where e.AccountId in:acctIds And e.EndDate >= Today And e.StartDate <= Today];
if(entls.isEmpty()==false){
for(Case c: Trigger.new){
if(c.EntitlementId == null && c.AccountId!= null){
for(Entitlement e:entls){
if(e.AccountId==c.AccountId){
c.EntitlementId = e.Id;
if(c.AssetId==null && e.AssetId!=null)
c.AssetId=e.AssetId;
break;
}
} // end for
}
} // end for
}
}
} // end if(contactIds.isEmpty()==false)
}
if(Trigger.isBefore && Trigger.isUpdate)
{
System.debug('entered if condition');
for(Case c : Trigger.new)
{
if (c.Assignment_Group__c != trigger.oldMap.get(c.Id).Assignment_Group__c){
System.debug('Updating logic');
List<Group> qid = [select Id from Group where Name = : c.Assignment_Group__c and Type = 'Queue'];
for(Group g : qid)
{
c.OwnerId = g.id;
System.debug('updated');
}
}}
}
if(Trigger.isBefore && Trigger.isUpdate)
{
for(Case c : Trigger.new)
{
if(c.Assignment_Group__c=='Tech Support'||c.Assignment_Group__c=='GD-IT'||c.Assignment_Group__c=='App-Support'||c.Assignment_Group__c=='GD-RM'||c.Assignment_Group__c=='GD-DB'||c.Assignment_Group__c=='Dev-Ops'||c.Assignment_Group__c=='App-Management'||c.Assignment_Group__c=='PDT-DS-Engg'||c.Assignment_Group__c=='PDT-US-Engg')
{
c.Group_Manager_Email__c = 'sargware#gmail.com'; c.Escalation_Level_2_Email__c ='sargware#gmail.com'; c.Escalation_Level_3_Email__c='sargware#gmail.com';
}
}
}
if(Trigger.isBefore && Trigger.isUpdate)
{
for(Case c : Trigger.new)
{
if(c.Internal_Impact__c == 'Low' && c.Internal_Urgency__c=='Low')
{
c.Priority='Planning';
}
if(c.Internal_Impact__c == 'High' && c.Internal_Urgency__c=='High')
{
c.Priority='Critical';
}
if(c.Status=='Pending User' || c.Status=='Pending Vendor')
{
c.IsStopped = True;
}
}
}
if((Trigger.isAfter && Trigger.isUpdate))
{
Set<Id> Ids = new Set<Id>();
Set<Id> IdR = new Set<Id>();
Set<Id> IdC = new Set<Id>();
List<SC_Problem_Case_Link__c> scprblm = new List<SC_Problem_Case_Link__c>();
List<SC_Problem_Case_Link__c> scprblmo = new List<SC_Problem_Case_Link__c>();
List<SC_Problem_Case_Link__c> scprblmc = new List<SC_Problem_Case_Link__c>();
for (Case cs: Trigger.new)
{
Case oldLead = Trigger.oldMap.get(cs.Id);
if (cs.Status == 'Tested' && Trigger.oldMap.get(oldLead .Id).Status=='Ready for Testing')
{
Ids.add(cs.Id);
}
if (cs.Status == 'ReOpen')
{
IdR.add(cs.Id);
}
if (cs.Status == 'Closed')
{
IdC.add(cs.Id);
}
}
for (SC_Problem_Case_Link__c rateSheet: [select Id,Status__c from SC_Problem_Case_Link__c where Status__c = 'Ready for Testing' AND Case__c in :Ids])
{
if (rateSheet.Status__c != 'Tested') {
rateSheet.Status__c = 'Tested';
//rateSheet.Case__c.Status= 'Awaiting Deployment';
scprblm.add(rateSheet);
}
}
if (!scprblm.isEmpty()) {
update scprblm;
}
for (SC_Problem_Case_Link__c rateSheet: [select Id,Status__c from SC_Problem_Case_Link__c where Status__c = 'Resolved' AND Case__c in :IdR])
{
// List<SC_Problem_Case_Link__c> accts = [Select Id, Status__c from SC_Problem_Case_Link__c where Id in : Trigger.old];
if (rateSheet.Status__c != 'Open') {
rateSheet.Status__c = 'Open';
scprblmo.add(rateSheet);
}
}
if (!scprblmo.isEmpty()) {
update scprblmo;
}
for (SC_Problem_Case_Link__c rateSheet: [select Id,Status__c from SC_Problem_Case_Link__c where Status__c = 'Resolved' AND Case__c in :IdC])
{
if (rateSheet.Status__c != 'Closed') {
rateSheet.Status__c = 'Closed';
scprblmc.add(rateSheet);
}
}
if (!scprblmc.isEmpty()) {
update scprblmc;
}
}
}

Hi SAdmin and welcome to the community.
You can use Developer Console in order to check which part of your code is not covered on your test class. Every time you run your test class you are able to see which lines of code is covered by clicking on Code Coverage dropdown on your main apex class.
This way you can see that the lines of code that are covered by tests are blue. Lines of code that aren’t covered are red. Lines of code that don’t require coverage (for example, curly brackets, comments, and System.debug calls) are left white.
Please check this guide out to find some more info.

Related

Once Case is created with updated fields, The updated fields should be updated in Account

trigger Ecare_Trg_UpdateContCoreData on Case (after update) {
List<AccountContactRelation> arcList = New List<AccountContactRelation>();
for(Case c: Trigger.New)
{
if(c.Status =='Closed' && c.Type == 'Commercial' && c.vlocity_cmt__Reason__c =='Change Request' && c.Description == 'Haupaddressdurang')
{
AccountContactRelation ct = [SELECT ContactId,AccountId From AccountContactRelation Where AccountId =: c.AccountId];
ct.Contact.FirstName = c.First_Name__c;
ct.Contact.LastName = c.Last_Name__c;
ct.Contact.Salutation = c.Salutation__c;
ct.Account.BillingCity = c.City__c;
ct.Account.BillingPostalCode = String.ValueOf(c.Postal_Code__c);
ct.Account.BillingStreet = c.Street__c;
arcList.add(ct);
System.debug(c.AccountId);
}
}
if(arcList.size()>0){
upsert arcList;
}
}
I need to update the update case details in Account By this trigger i am not able update how we can do it?

i am having problem where recursion is happing in apex triggers it start where i have written PROBLEM HERE

this part works fine
1.no problem here in this part of code.
trigger intertask_3 on Campaign (before insert, before update,after update) {
List<CampaignMember> updList = new List<CampaignMember>();
if(trigger.isbefore && trigger.isinsert){
for(Campaign camp : trigger.new){
if(camp.Capping__c == true){
if(camp.Capping_Value__c == null || camp.Capping_Value__c <= 1){
camp.Capping_Value__c.addError(' value cant be empty, 0 and negative');
}
}
}
}
//for error
if(trigger.isbefore && trigger.isupdate){
set<id> campId = new set<id>();
for(Campaign camp : trigger.new){
if(camp.Name != null){
campId.add(camp.Id);
}
}
list<CampaignMember> cm = [select id from CampaignMember where status = 'Registered' and CampaignId in : campId];
integer count = integer.valueOf(cm.size());
//system.debug(count);
for(Campaign campM : trigger.new ){
//system.debug(campM.Capping_Value__c );
if(campM.Capping__c == true){
if(campM.Capping_Value__c < count){
//system.debug(count);
campM.Capping_Value__c.addError('value cant be less than registered member');
}else if (campM.Capping_Value__c == count){
campM.Capping_Value__c.addError('cant update same value');
}
}
}
}
if(trigger.isafter && trigger.isupdate){
set<id> campId = new set<id>();
for(Campaign camp : trigger.new){
Campaign campo = trigger.oldMap.get(camp.Id);
if(camp.Capping__c == true){
if(camp.Capping_Value__c != campo.Capping_Value__c ){
campId.add(camp.Id);
}
}
}
Map<id,integer> cmapIdandCMno = new Map<id,integer>();
List<Campaign> campContainReg = [select id,(select id from CampaignMembers where status = 'Registered') from Campaign where id in : campId];
for(Campaign camp : campContainReg){
cmapIdandCMno.put((id)camp.Id,(integer)camp.CampaignMembers.size());
}
// number of registered campaignmember
//list<CampaignMember> cm = [select id from CampaignMember where status = 'Registered' and CampaignId in : campId];
//integer count = integer.valueOf(cm.size());
//all CampaignMember
//for(CampaignMember campM :[select id,status,Campaign.Id,Campaign.Capping_Value__c from CampaignMember where CampaignId in : cmapIdandCMno.keySet() ] ){
//integer size = integer.valueOf(cmapIdandCMno.get(campM.Campaign.Id));
// system.debug(size);
// }
/*
list<CampaignMember> camMno = [select id,Campaign.Id from CampaignMember where CampaignId in :cmapIdandCMno.keySet() ];
integer size = integer.valueOf(camMno.Campaign.Id);
system.debug(size);
}*/
**PROBLEM FORM HERE **
problem with size varibale , i could not understand where to put it so that it does not loop 5 times at the same time.
it looks like my else statement is not working at all.
//in this for loop all members are getting registered instead of following the if else
statement
for(CampaignMember campM :[select id, status, Campaign.Id, Campaign.Capping_Value__c from CampaignMember where CampaignId in : cmapIdandCMno.keySet() ] ){
//for(id mapid : cmapIdandCMno.keySet()){
integer size = integer.valueOf(cmapIdandCMno.get(campM.Campaign.Id));
//system.debug(size);
//}
if(size < campM.Campaign.Capping_Value__c && (campM.Status == 'Waitlisted' || campM.Status == 'Engaged')){
campM.Status= 'Registered';
updList.add(campM);
size++;
system.debug(size);
}
else if( size == campM.Campaign.Capping_Value__c){
campM.Status= 'Waitlisted';
updList.add(campM);
}
}
//system.debug(size);
}
update updList ;
}

start_time__c field of custom object is not working in trigger i don't no what to do?

I have to do this:-
If an attendee has registered to parallel sessions (Sessions happening at the same time/overlapping sessions), then a checkbox (Registered_To_Parallel_Sessions__c) on the Attendee(Lead) object must be checked automatically.
This is my trigger:-
trigger RegisteredToParallelSession on Session_Attendee__c (after insert,before insert) {
list<session_attendee__C> sa2 = [select attendee__c, session__c, session__r.id,session__r.name, session__r.Start_Time__c from Session_attendee__c];
list<lead> l = [select id, Registered_To_Parallel_Session__c from lead];
list<session__c> s = [select id, start_time__c from session__c];
for(session_attendee__c sa4 : trigger.new){
for(session__c s2 : s){
for(lead l1 : l){
if(l1.Id == sa4.Attendee__c && s2.id == sa4.session__c && s2.Start_Time__c == sa4.session__r.Start_Time__c ) // this condition is not working
{
l1.Registered_To_Parallel_Session__c = true;
update l1;
}
}
}
}
}
This if(sa4.session__c && s2.Start_Time__c == sa4.session__r.Start_Time__c ) condition in above code is not working
please help & Thanks!

EF Core 3.x: duplicate value

I have the following code:
public class DeviceVerizon
{
public int DeviceId { get; set; }
public string InternalDeviceId { get; set; }
}
and
public class DeviceVerizonMap : IEntityTypeConfiguration<DeviceVerizon>
{
public void Configure(EntityTypeBuilder<DeviceVerizon> builder)
{
builder.ToTable(nameof(DeviceVerizon));
builder.HasKey(d => d.DeviceId);
builder.HasIndex(v => v.InternalDeviceId).IsUnique();
builder.HasOne(o => o.Device)
.WithOne(o => o.VerizonData)
.HasForeignKey<DeviceVerizon>(a => a.DeviceId)
.OnDelete(DeleteBehavior.Cascade)
.IsRequired()
;
}
}
so, InternalDeviceId is just unique index.
some code change InternalDeviceId for existing record and add new record with the previous InternalDeviceId.
So, localDevice.VerizonData.InternalDeviceId = 1420531689
I update it for new (remoteDevice.VerizonData.InternalDeviceId = '111111111')
localDevice.VerizonData = remoteDevice.VerizonData;
_context.Devices.Update(localDevice);
then add new record with remoteDevice.VerizonData.InternalDeviceId = 1420531689:
_context.Devices.Add(remoteDevice);
and after it I call:
await _context.SaveChangesAsync();
but I get an exception:
Cannot insert duplicate key row in object 'dbo.DeviceVerizon' with
unique index 'IX_DeviceVerizon_InternalDeviceId'. The duplicate key
value is (1420531689).
The full code:
foreach (var remoteDevice in remoteVerizonDevices)
{
var localDevice = allLocalDevicesWithIMEI.Where(a =>
(string.IsNullOrWhiteSpace(remoteDevice.IMEI)
&& a.VerizonData != null
&& a.VerizonData.InternalDeviceId == remoteDevice.VerizonData.InternalDeviceId
&& a.IMSI == remoteDevice.IMSI && a.ICCID == remoteDevice.ICCID)
|| a.IMEI == remoteDevice.IMEI).FirstOrDefault();
if (localDevice != null) // device with such imei already exists or IMEI is empty on Verizon, but InternalDeviceId is the same and ICCID with IMSI are the same
{
var verizonStatus = remoteDevice.VerizonData.State.ConvertToDeviceStatusFromVerizonStatus();
var existingRequest = _context.VerizonRequests.Where(a => a.DeviceId == localDevice.Id && a.Result == VerizonRequestResult.Pending).FirstOrDefault();
if (verizonStatus == DeviceStatus.Active && remoteDevice.IsVerizonLastActiveMoreThanDays(60))
{
// existing request for this device does not exist, create new
if (existingRequest == null)
{
localDevice.Status = DeviceStatus.PendingSuspend;
localDevice.DateStatusChanging = DateTime.UtcNow;
localDevice.LastStatusChangeSource = DeviceStatusChangeSource.Verizon;
// create verizon request to change status, because device is offline more than 60 days
verizonSuspensionList.Add(localDevice.Id);
}
}
else
{
// Is Verizon status of device is different than locally?
if (localDevice.Status != verizonStatus)
{
// check whether we have active verizon request, if not, then
if (existingRequest == null)
{
// device is suspended on suremdm, we should suspend on Verizon
if (localDevice.Status == DeviceStatus.Suspended
&& verizonStatus == DeviceStatus.Active)
{
if (localDevice.Tablet != null && localDevice.Tablet.TabletGroup.GroupName == SpecialSureMdmGroups.Suspended)
verizonSuspensionList.Add(localDevice.Id);
}
else if (localDevice.Status != DeviceStatus.Suspended && verizonStatus == DeviceStatus.Suspended)
{
// if device is suspended on verizon, we need to suspend on SureMdm
localDevice.Status = DeviceStatus.PendingSuspend;
localDevice.DateStatusChanging = DateTime.UtcNow;
localDevice.LastStatusChangeSource = DeviceStatusChangeSource.Verizon;
if (localDevice.Tablet != null)
{
localDevice.Tablet.SuspensionDate = DateTime.UtcNow;
sureMdmSuspensionList.Add(new Core.Dto.DeviceManagement.SureMdm.SureMdmMoveDeviceToSuspendedGroupDto
{
TabletId = localDevice.Tablet.TabletId,
CurrentGroupId = localDevice.Tablet.TabletGroupId
});
}
}
else
{
// other cases that device on verizon has different status, that locally
VerizonStatusIsDifferentEvent?.Invoke(
remoteDevice: remoteDevice,
verizonStatus: remoteDevice.VerizonData.State.ConvertToDeviceStatusFromVerizonStatus(),
localStatus: localDevice.Status);
}
}
}
}
var changes = DeviceIsChanged(remoteDevice, localDevice);
if (changes != null && changes.Count > 0)
modifiedDevices.Add((localDevice, changes));
var continueToUpdate = true;
// if verizon data does not exist, add it
if (localDevice.VerizonData == null)
{
var existingInternalVerizonDeviceIdRecord = allDeviceVerizons.Where(a => a.InternalDeviceId == remoteDevice.VerizonData.InternalDeviceId).FirstOrDefault();
if (existingInternalVerizonDeviceIdRecord != null)
{
DeviceWithTheSameVerizonDeviceIdAlreadyExistsEvent?.Invoke(remoteDevice: remoteDevice,
localDevice: existingInternalVerizonDeviceIdRecord.Device,
verizonDeviceId: remoteDevice.VerizonData.InternalDeviceId);
continueToUpdate = false;
}
}
if (continueToUpdate)
{
localDevice.VerizonData = remoteDevice.VerizonData;
if (!string.IsNullOrWhiteSpace(remoteDevice.ICCID))
localDevice.ICCID = remoteDevice.ICCID;
localDevice.EID = remoteDevice.EID;
localDevice.ESN = remoteDevice.ESN;
if (!string.IsNullOrWhiteSpace(remoteDevice.IMSI))
localDevice.IMSI = remoteDevice.IMSI;
if (!string.IsNullOrWhiteSpace(remoteDevice.MDN))
localDevice.MDN = remoteDevice.MDN;
localDevice.MEID = remoteDevice.MEID;
localDevice.MIN = remoteDevice.MIN;
localDevice.MSISDN = remoteDevice.MSISDN;
localDevice.SKU = remoteDevice.SKU;
localDevice.SyncVerizon = true;
if (string.IsNullOrWhiteSpace(localDevice.Name))
localDevice.Name = localDevice.IMEI;
if (!localDevice.DeviceModelId.HasValue)
{
var verizonGroup = allVerizonGroups.Where(a => a.VerizonGroupName == remoteDevice.VerizonData.GroupName).FirstOrDefault();
if (!verizonGroup.DeviceModelId.HasValue)
VerizonGroupIsNotLinkedWithDeviceModelEvent?.Invoke(remoteDevice);
else
localDevice.DeviceModelId = verizonGroup.DeviceModelId;
}
_context.Devices.Update(localDevice);
}
}
else
{
// validate by Internal Verizon DeviceId
var existingInternalVerizonDeviceIdRecord = allDeviceVerizons.Where(a => a.InternalDeviceId == remoteDevice.VerizonData.InternalDeviceId).FirstOrDefault();
if (existingInternalVerizonDeviceIdRecord != null)
{
DeviceWithTheSameVerizonDeviceIdAlreadyExistsEvent?.Invoke(remoteDevice: remoteDevice,
localDevice: existingInternalVerizonDeviceIdRecord.Device,
verizonDeviceId: remoteDevice.VerizonData.InternalDeviceId);
}
else
{
// add new record
if (!string.IsNullOrWhiteSpace(remoteDevice.IMEI))
remoteDevice.Name = remoteDevice.IMEI;
else if (!string.IsNullOrWhiteSpace(remoteDevice.VerizonData.PrimaryPlaceOfUseFirstName) || !string.IsNullOrWhiteSpace(remoteDevice.VerizonData.PrimaryPlaceOfUseLastName))
remoteDevice.Name = $"{remoteDevice.VerizonData.PrimaryPlaceOfUseFirstName} {remoteDevice.VerizonData.PrimaryPlaceOfUseLastName}";
else
remoteDevice.Name = Core.Constants.Common.Undefined;
// set device Model
var verizonGroup = allVerizonGroups.Where(a => a.VerizonGroupName == remoteDevice.VerizonData.GroupName).FirstOrDefault();
if (!verizonGroup.DeviceModelId.HasValue)
VerizonGroupIsNotLinkedWithDeviceModelEvent?.Invoke(remoteDevice);
else
remoteDevice.DeviceModelId = verizonGroup.DeviceModelId;
// set device status
remoteDevice.Status = remoteDevice.VerizonData.State.ConvertToDeviceStatusFromVerizonStatus();
if (!string.IsNullOrWhiteSpace(remoteDevice.VerizonData.CarrierName))
{
var verizonCarrier = allVerizonCarriers.Where(a => a.VerizonCarrierName == remoteDevice.VerizonData.CarrierName).FirstOrDefault();
if (verizonCarrier.CarrierId.HasValue)
remoteDevice.CarrierId = verizonCarrier.CarrierId;
else
{
// notify that carrier is not found locally
LocalCarrierIsNotFoundForNewDeviceEvent?.Invoke(remoteDevice);
}
}
remoteDevice.SyncVerizon = true;
_context.Devices.Add(remoteDevice);
newDevices.Add(remoteDevice);
}
}
}
await _context.SaveChangesAsync();
why so? only one record has 1420531689, old was updated for new value (111111111) and it saved in the one transaction... How to do it correctly?

Salesforce Trigger Test Class

below is my Apex Trigger. I am a beginner and trying to write its test class but continuously getting error "System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Error: You can't select products until you've chosen a price book for this opportunity on the products related list.: []".
trigger TrgrOptyHighestCustmorePrice on Opportunity (before insert, before update)
{
public Id oid;
public String bidType;
public String BUCode;
for(Opportunity o : trigger.new)
{
oid = o.Id;
bidType = o.BidType__c;
BUCode = o.Business_Line_BU__c;
}
List<OpportunityLineItem> oliList = new list<OpportunityLineItem>([SELECT id, Customer_Price__c, ReCat_Product_Line__c
FROM OpportunityLineItem
WHERE OpportunityId =: oid ORDER BY
Customer_Price__c DESC LIMIT 1]);
for(OpportunityLineItem oli : oliList)
{
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.619';
}
if(bidType == 'Competitive' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.620';
}
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.622';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.624';
}
if(bidType == 'Sole Sourced' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.621';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.623';
}
}
for(Opportunity opt : trigger.new)
{
opt.Business_Line_BU__c = BUCode;
}
}
Test Class
#isTest(seeAllData=true)
public class Test_TrgrOptyHighestCustmorePrice {
private static testmethod void TrgrOptyHighestCustmorePriceTest(){
Test.startTest();
//Insert a test product.
Product2 p1 = new Product2(Name='Product Monthly 1111', isActive=true, CurrencyIsoCode='USD', ReCat_Product_Line__c = 'DMS');
insert p1;
// Get standard price book ID.
Id pricebookId = Test.getStandardPricebookId();
// Insert a price book entry for the standard price book.
PricebookEntry standardPrice = new PricebookEntry(
Pricebook2Id = pricebookId, Product2Id = p1.Id,
UnitPrice = 10000, IsActive = true);
insert standardPrice;
Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
insert customPB;
PricebookEntry customPrice = new PricebookEntry(
Pricebook2Id = customPB.Id, Product2Id = p1.Id,
UnitPrice = 12000, IsActive = true);
insert customPrice;
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619',
PriceBook2 = customPB);
insert opt;
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id);
insert optLI;
update opt;
Test.stopTest();
}
}
I am unable to understand how can I test my simple trigger.
Its because u do not fill all required fields for the Opportunity Line Item. See: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_opportunitylineitem.htm for required fields.
This as an example will work:
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id, TotalPrice = 100, PricebookEntryId=customPrice.Id, Quantity =3);
First Insert the opportunity.
Then update the opportunity with the pricebookid.
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619'
);
insert opt;
opt.PriceBook2 = customPB;
update opt;