[SalesForce] Test method with query string

I have the following test method and keep getting: List has no rows for assignment to SObject.

    public static testMethod void TestChurchName() {

    PageReference pageRef = Page.ChurchHistoryDev;
    Test.setCurrentPage(pageRef);

    ChurchHistoryDevController con = new ChurchHistoryDevController();
    ApexPages.currentPage().getParameters().put('id', '1290');
    con.setChurchName();
    String ch = con.ChurchName;

    System.assertEquals('Metropolitan Baptist Church-Largo, MD', ch);
}

My here is my controller and the setChurchName() function.

    public ChurchHistoryDevController() {
    ChurchId = ApexPages.currentPage().getParameters().get('id');
}

//*****************************************************
// Church name get and set
//*****************************************************
public void setChurchName() {
    Account acct = [select Name from Account where Customer_ID__c = :ChurchId];
    ChurchName = acct.Name;
}

My visualforce page works fine. I just can't get the test to work and since SF is griping at me I guess I have to create tests 🙂 Any idea what I'm doing wrong in my test? I know that it's blowing up because of the SELECT statement in setChurchName() but why isn't that value being passed to my class with the getParameters().put() method?

Thanks,
Randy

Best Answer

Because you need to insert an Account prior to running your tests.

Simply do the following prior to the test:

public static testMethod void TestChurchName()
{
    Account TestAccount = new Account(Name = 'Metropolitan Baptist Church-Largo, MD', 
        Customer_ID__c = '1290' /*Populate the account with other fields*/);
    INSERT TestAccount;
    PageReference pageRef = Page.ChurchHistoryDev;
    Test.setCurrentPage(pageRef);
    ApexPages.currentPage().getParameters().put('id', TestAccount.Customer_ID__c);

    ChurchHistoryDevController con = new ChurchHistoryDevController();

You can always put @isTest(SeeAllData=true) at the top of your test. But when you are running the test, you must always have the record there or the test will fail. That means, if someone accidentally deletes the record, your tests will fail. That includes when you are deploying because when you deploy to an org, those records won't exist. That's why I recommend the approach above (unless you cannot create the object in Apex - like a PriceBook).

Related Topic