Salesforce Controller Extension Testing: System.QueryException: List has no rows for assignment to SObject

StackOverflow https://stackoverflow.com/questions/20893137

  •  23-09-2022
  •  | 
  •  

Question

I'm looking for some help testing a controller extension. I keep receiving the error: "System.QueryException: List has no rows for assignment to SObject" which is referring to the SOQL statement in my class.

Class

public class productdata {

public productdata(ApexPages.StandardController controller) {
}

public String getTag(){
    Product2 prod;
    prod = [SELECT Name FROM Product2 WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    return Prod.Name;
}

Test Class

@isTest

private class TestProductData { static testMethod void TestProductDataMethod(){

    Product2 TP = new Product2(Name='TestRecord');
    insert TP;
    System.assertEquals('TestRecord', TP.name);

    PageReference pageRef = page.productpage;
    Test.setCurrentPage(pageRef);

    ApexPages.StandardController sc = new ApexPages.standardController(TP);                
    productdata controller = new productdata(new ApexPages.StandardController(TP));       
    ApexPages.currentPage().getParameters().put('id', '01t300000007hKrAAI');

    controller.getTag();
    }

Thanks!

Was it helpful?

Solution

You shouldn't manually assign your record ids (as they will change with each run of the test).

ApexPages.currentPage().getParameters().put('id', '01t300000007hKrAAI');

Instead do:

ApexPages.currentPage().getParameters().put('id', TP.id);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top