+ Start a Discussion
teknicsandteknicsand 

Test method for a query

I have a query

public Pricebook2 getPricebook2()
{
Opportunity opp_info = getOpportunity();
Pricebook2 pricebook_info = [select Id, P.Name, P.IsActive, P.Description from Pricebook2 P
where P.id = : opp_info.Pricebook2Id];
return pricebook_info;

 

How would I test this in my test class?

 

This is what I have in my test class

 

Pricebook2 pb_info = new Pricebook2 (name='testbook',description='asdsdfsf', IsActive=true);
insert pb_info;
controller.getPricebook2();

 where controller is an object of the visualforce controller I'm trying to test.

 

But I get an error message that says

 

 

Class.myOpportunityController.getPricebook2: line 40, column 37 Class.myOpportunityTestClass.myControllerTest: line 67, column 10 System.QueryException: List has no rows for assignment to SObject

 

 

 

 

 

 

Message Edited by teknicsand on 04-02-2009 04:03 AM
jeffdonthemicjeffdonthemic

Have you looked at the documentation for unit testing for controllers and extensions? See if this helps?

 

Jeff Douglas
Informa Plc
http://blog.jeffdouglas.com

teknicsandteknicsand

Product2 testpd = new Product2 (name='test product'); testpd.productcode = 'test pd code'; insert testpd; Pricebook2 testpb = new Pricebook2 (name='test pricebook'); testpb.description = 'this is a test'; testpb.IsActive = true; // testpb.IsStandard = true; insert testpb; PricebookEntry testpbe = new PricebookEntry (); testpbe.pricebook2id = testpb.id; testpbe.product2id = testpd.id; testpbe.IsActive = True; testpbe.UnitPrice = 233; testpbe.UseStandardPrice = false; insert testpbe; controller.getPricebook2();

 I get a STANDARD_PRICE_NOT_DEFINED; No standard price defined for this product error. How would I define the standard price? 

jeffdonthemicjeffdonthemic

I would just query for the existing standard pricebook (since each org already has one) instead of trying to create it. You can then use this id for your pricebookentry. Here is some more documentation that might help.

 

 

Pricebook2 s = [select id from Pricebook2 where IsStandard = true];

 

Good luck

 

Jeff Douglas
Informa Plc
http://blog.jeffdouglas.com

 

bprakashbprakash

when i use  this in test code and running the test

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

Please give me your advice on this.

thanks

Bhanu

craigmhcraigmh

http://stackoverflow.com/questions/9164986/how-do-i-avoid-standard-price-not-defined-when-unit-testing-an-opportunitylineit

 

Might have to use this:

 

@isTest (seeAllData=true)

 

Using the standard pricebook is a good idea, but you can't insert one from a test class, and I've even had issues where the standard pricebook is inactive. The change that SFDC made to testing for Spring '12 is causing logistical nightmares.