function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chandu007Chandu007 

Is it mandatory to use SeeAllData=true to get Pricebookentry object in test class?

I am doing some modifications to existing test class and removed SeeAllData=true(for best practise). now i am getting below error. So, now i want to know whether SeeAllData=true when we are using Pricebook object in test class.

Error:-

System.QueryException: List has no rows for assignment to SObject

errored line from test class:-
Pricebook2 pb = [select Id from Pricebook2 where isStandard=true limit 1]; 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Chandu,

Greetings to you!

You can use Test.getStandardPricebookId() to get the Id of the current Pricebook. 

Below is the sample code:
 
//Create Product
Product2 pro = new Product2(Name = 'iPhone X', Family = 'Mobile');
Insert pro;
 
//Instantiate the Pricebook2 record with StandardPricebookId
Pricebook2 standardPricebook = new Pricebook2(
    Id = Test.getStandardPricebookId(),
    IsActive = true
);
 
//Execute an update DML on the Pricebook2 record, to make IsStandard to true
Update standardPricebook;
 
//Query for the Pricebook2 record, to check IsStandard field
standardPricebook = [SELECT Id, IsStandard FROM Pricebook2 WHERE Id = :standardPricebook.Id];
//It should return true
System.assertEquals(true, standardPricebook.IsStandard);
 
 
//Create the PricebookEntry
PricebookEntry pbe = new PricebookEntry(
    Pricebook2Id = standardPricebook.Id,
    Product2Id = pro.Id,
    UnitPrice = 1020,
    IsActive = true
);
Insert pbe;
 
//Query the PricebookEntry record
pbe = [SELECT Id, Pricebook2.IsStandard FROM PricebookEntry];
//It should return true
System.assertEquals(true, pbe.Pricebook2.IsStandard);

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Chandu007Chandu007
Hi Khan,

I have modified my test class as you suggested above but it failing again with below error and trigger CMDM_Post_Tention_Weight_Rollup is another trigger which is not currently i am working.

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CMDM_Post_Tention_Weight_Rollup: execution of AfterInsert

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.CMDM_Post_Tention_Weight_Rollup: line 4, column 1: []