You need to sign in to do that
Don't have an account?

Help with test method
Hello,
I have extension class for Opportunity that redirect after save. I have written test method as well for this but I am struggling to get full code coverage.
so the test method doesn't cover "return contoller.save()" from extension class. Can someone please point me where i am doing wrong?
Thanks,
Class:
Public Class NewBookingExtension { Public Opportunity opps {get; set;} Private ApexPages.StandardController controller; Public NewBookingExtension(ApexPages.StandardController controller){ this.controller = controller; } Public PageReference saveAndService() { if(controller.save() !=null) { PageReference saveAndServ = Page.AddServices; saveAndServ.setRedirect(true); saveAndServ.getParameters().put('id',controller.getId()); return saveAndServ; } return controller.save(); /* this line doesn't cover on test method. */ } }
Test Class:
@IsTest(SeeAllData=true) private class NewBookingExtensionTest { static testMethod void myUnitForExtensionTest() { Pricebook2 pb = [Select Id, Name From Pricebook2 Where IsStandard = true Limit 1]; /* Setup a basic opportunity */ Account act = [SELECT Id from Account LIMIT 1]; Opportunity o = new Opportunity(); o.Name = 'TEST for new booking'; o.AccountId = act.Id; o.CloseDate = Date.today(); o.StageName = 'Insert'; Database.insert(o); Apexpages.Standardcontroller controllers = new Apexpages.Standardcontroller(o); NewBookingExtension newBooking = new NewBookingExtension(controllers); ApexPages.currentPage().getParameters().put('id',+o.Id); System.assert(newBooking.saveAndService()!=null); }
The first controller.save() would have to return null. The way your code is written, this means you'll have to trigger a validation exception (e.g. by leaving CloseDate blank).
This is usually more of an annoyance to test, so I usually write my code like this:
This makes code coverage easier; now you only have to test the successful save, and not the failed save.
All Answers
the first two mistakes i found in your code is your are querying for the Account Id and PB.
what ever the mandataroy fields are there and if some of them are lookups. like Account. you should create account and pb and insert them then pass their ids in the OPPORTUNITY.
Account act =new Account();
act.Name = 'xyz';
Insert act;
similarly Pb then you can pass act.Id in the OPPortunity.
If this answers your question make this as asolution. and give KUDOS please
The first controller.save() would have to return null. The way your code is written, this means you'll have to trigger a validation exception (e.g. by leaving CloseDate blank).
This is usually more of an annoyance to test, so I usually write my code like this:
This makes code coverage easier; now you only have to test the successful save, and not the failed save.
Thanks sfdcfox! You are awsome! I have learned new approch.