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
Tripti Nirmal GuptaTripti Nirmal Gupta 

System.QueryException: List has no rows for assignment to SObject when running Test Class Product2Tests

Class.Constants: line 11, column 1
Class.Product2Extension.AddRows: line 11, column 1
Class.Product2Extension.<init>: line 7, column 1
Class.Product2Tests.Product2Extension_UnitTest: line 14, column 1

@isTest (seeAllData=false)
private class Product2Tests {

    /**
     * @name product2Extension_UnitTest
     * @description UnitTest for product2Extension
    **/
    static TestMethod void Product2Extension_UnitTest(){
        Test.startTest();
        PageReference pageRef = Page.Product2New;
        Test.setCurrentPage(pageRef);
        Product2 prod = new Product2(Name = 'Test Product', isActive=true);     
           ApexPages.StandardController stdctrl = new ApexPages.StandardController(prod);
        Product2Extension ext = new Product2Extension(stdctrl);
        System.assertEquals(Constants.DEFAULT_ROWS, ext.productsToInsert.size());        
            
        ext.addRows();
        System.assertEquals(Constants.DEFAULT_ROWS * 2, ext.productsToInsert.size());
        
        for (Integer i = 0; i < 5; i++) {
            Product2Extension.ProductWrapper wrapper = ext.productsToInsert[i];
            
            Product2 testProduct = new Product2();
            testProduct.Name = 'Test Product ' + i;
            testProduct.IsActive = true;
            testProduct.Initial_Inventory__c = 20;
            testProduct.Family = Constants.PRODUCT_FAMILY[0].getValue();
            wrapper.productRecord = testProduct;
            
            PricebookEntry testEntry = new PricebookEntry();
            testEntry.IsActive = true;
            testEntry.UnitPrice = 10;
            wrapper.pricebookEntryRecord = testEntry;
        }
        ext.save();
        Test.stopTest();
        
        List<Product2> createdProducts = [SELECT Id from Product2
                                          WHERE name like 'Test Product%'];
        System.assertEquals(5, createdProducts.size());      
    }
}

/**
 * @name TestDataFactory
 * @description Contains methods to construct and/or validate commonly used records
**/
public with sharing class TestDataFactory {

    /**
     * @name ConstructCollaborationGroup
     * @description
    **/
    public static CollaborationGroup ConstructCollaborationGroup(){
        //ToDo: Ensure this method returns a single Chatter CollaborationGroup
        //    whose Name starts with 'TEST' followed by the INVENTORY_ANNOUNCEMENTS constant
        //    and configured so anyone can join, see and post updates.
        
        CollaborationGroup cg = new CollaborationGroup();
        cg.Name = 'Test'+Constants.INVENTORY_ANNOUNCEMENTS;
        cg.CollaborationType = 'Public';
        return cg;
    }
    

    /**
     * @name CreateProducts
     * @description Constructs a list of Product2 records for unit tests
    **/
    public static List<Product2> ConstructProducts(Integer cnt){
        //ToDo: Ensure this method returns a list, of size cnt, of uniquely named Product2 records
        //  with all the required fields populated
        //  and IsActive = true
        //  an Initial Inventory set to 10
        //  and iterating through the product family picklist values throughout the list.
        List<Product2> prodList = new List<Product2>();
        List<Schema.PicklistEntry> pleList = Constants.PRODUCT_FAMILY;      
        for (Integer i=0; i< cnt; i++){
            Integer n = math.mod(i,pleList.size());
            Product2 prod = new Product2();
            prod.Name = 'Test Product ' + pleList[n].getValue() + ' ' + i;
            prod.IsActive = true;
            prod.Initial_Inventory__c = 10;
            prod.Family = pleList[n].getValue();
            prodList.add(prod);
        }
        return prodList;
    }

    /**
     * @name CreatePricebookEntries
     * @description Constructs a list of PricebookEntry records for unit tests
    **/
    public static List<PricebookEntry> ConstructPricebookEntries(List<Product2> prods){
        //ToDo: Ensure this method returns a corresponding list of PricebookEntries records
        //  related to the provided Products
        //  with all the required fields populated
        //  and IsActive = true
        //  and belonging to the standard Pricebook
        
        List<PriceBookEntry> pbeList = new List<PriceBookEntry>();        
        for (Product2 prod : prods){
            PriceBookEntry pbe = new PriceBookEntry();
            pbe.IsActive = true;
            pbe.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
            pbe.Product2Id = prod.Id;
            pbe.UnitPrice = 100;
            pbeList.add(pbe);
        }
        return pbeList;
    }
    /**
     * @name CreateAccounts
     * @description Constructs a list of Account records for unit tests
    **/
    public static List<Account> ConstructAccounts(Integer cnt){
        //ToDo: Ensure this method returns a list of size cnt of uniquely named Account records
        //  with all of the required fields populated.
        List<Account> acctList = new List<Account>();     
        for (Integer i=0; i< cnt; i++){
            Account acct = new Account();
            acct.Name = 'Test Acct ' + i;
            acctList.add(acct);
        }
        return acctList;
    }

    /**
     * @name CreateContacts
     * @description Constructs a list of Contact records for unit tests
    **/
    public static List<Contact> ConstructContacts(Integer cnt, List<Account> accts){
        //ToDo: Ensure this method returns a list, of size cnt, of uniquely named Contact records
        //  related to the provided Accounts
        //  with all of the required fields populated.
        List<Contact> contList = new List<Contact>();
        
        for (Integer i = 0; i < cnt; i++ ){
            Contact cont = new Contact();
            cont.LastName = 'Test Cont ' + i;
            cont.AccountId = accts[i].Id;
            contList.add(cont);
        }
        return contList;
    }

    /**
     * @name CreateOrders
     * @description Constructs a list of Order records for unit tests
    **/
    public static List<Order> ConstructOrders(Integer cnt, List<Account> accts){
        //ToDo: Ensure this method returns a list of size cnt of uniquely named Order records
        //  related to the provided Accounts
        //  with all of the required fields populated.
        List<Order> ordList = new List<Order>();     
        for (Integer i=0; i<cnt; i++){
            Order ord = new Order();
            ord.Name = accts[i].Name + ' Test Order ' + i;
            ord.EffectiveDate = System.today();
            ord.AccountId = accts[i].Id;
            ord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
            ord.Status = Constants.DRAFT_ORDER_STATUS;
            ordList.add(ord);
        }
        return ordList;
    }

    /**
     * @name CreateOrderItems
     * @description Constructs a list of OrderItem records for unit tests
    **/
    public static List<OrderItem> ConstructOrderItems(integer cnt, list<pricebookentry> pbes, list<order> ords){
        //ToDo: Ensure this method returns a list of size cnt of OrderItem records
        //  related to the provided Pricebook Entries
        //  and related to the provided Orders
        //  with all of the required fields populated.
        //  Hint: Use the DEFAULT_ROWS constant for Quantity as it will be used in the next challenge
        List<OrderItem> ordItemList = new List<OrderItem>();
        
        for (Integer i=0; i< cnt; i++){
            OrderItem ordItem = new OrderItem();
            ordItem.OrderId = ords[i].Id;
            ordItem.Quantity = Constants.DEFAULT_ROWS;
            ordItem.PricebookEntryId = pbes[i].Id;
            ordItem.UnitPrice = pbes[i].UnitPrice;
            ordItemList.add(ordItem);
        }
        return ordItemList;
    }

    /**
     * @name SetupTestData
     * @description Inserts accounts, contacts, Products, PricebookEntries, Orders, and OrderItems.
    **/
 
    public static void InsertTestData(Integer cnt){
        //ToDo: Ensure this method calls each of the construct methods
        //  and inserts the results for use as test data.
        
        CollaborationGroup cg = ConstructCollaborationGroup();
        insert cg;
        List<Product2> prodList = ConstructProducts(cnt);
        insert prodList;
        List<PricebookEntry> pbeList = ConstructPricebookEntries(prodList);
        insert pbeList;
        List<Account> acctList = ConstructAccounts(cnt);
        insert acctList;
        List<Contact> contList = ConstructContacts(cnt, acctList);
        insert contList;
        List<Order> ordList = ConstructOrders(cnt, acctList);
        insert ordList;
        List<OrderItem> ordItemList = ConstructOrderItems(cnt, pbeList, ordList);
        insert ordItemList;
        
        /*
        delete cg;
        delete ordItemList;
        delete ordList;
        delete pbeList;
        delete prodList;       
        delete contList;
        delete acctList;
        */
    }
    
    public static void VerifyQuantityOrdered(Product2 originalProduct, Product2 updatedProduct, Integer qtyOrdered){
        System.assertEquals(originalProduct.Quantity_Ordered__c + qtyOrdered, updatedProduct.Quantity_Ordered__c);
        
    }

    
}

 
Tripti Nirmal GuptaTripti Nirmal Gupta
This is my Constants class
public class Constants {
    public static final Integer DEFAULT_ROWS = 5 ;
    public static final String SELECT_ONE = Label.Select_one ;
    public static final String INVENTORY_LEVEL_LOW = Label.Inventory_Level_Low ;
    public static final List<Schema.PicklistEntry> PRODUCT_FAMILY = Product2.Family.getDescribe().getPicklistValues() ;
    public static final String DRAFT_ORDER_STATUS = 'Draft' ;
    public static final String ACTIVATED_ORDER_STATUS = 'Activated' ;
    public static final String INVENTORY_ANNOUNCEMENTS = 'Inventory Announcements' ;
    public static final String ERROR_MESSAGE = 'An error has occurred, please take a screenshot with the URL and send it to IT.' ;
    public static final Id STANDARD_PRICEBOOK_ID =  [SELECT Id From Pricebook2 WHERE IsStandard = true].Id ;
    
}
Abdul KhatriAbdul Khatri
It seems like you do not have any Pricebook2, therefore the following line in your Constants class is blowing off.
public static final Id STANDARD_PRICEBOOK_ID =  [SELECT Id From Pricebook2 WHERE IsStandard = true].Id;
It looks like you are missing pricebook. Can you verify by running the same SOQL in the QueryEditor. There is another solution but I think you need pricebook, the other solution will ignore that.
Tripti Nirmal GuptaTripti Nirmal Gupta
Hi Abdul, I have verified the Pricebook is there. Actually I cannot access any of the variables from my Constants class in Test class. I tried to run the method from Test class in anonymous window after removing @isTest and it works fine. I believe test class is not able to access the variables from Constants class. My other test class is also failing with the same issue.
Just to add, testclass and main class are in API version 38 but the Constants class is with API version 44. Not sure if that could be the issue
Abdul KhatriAbdul Khatri
I think differently because that is the reason you are getting that issue because your test class is reading that line. That error only happens when there is no data available for that condition. Normally you can prevent that error by changing your variable from Id to List<Id> but then you need to change your code everywhere to check if the List is empty or not before assignment.

Can you share the screen shot of what you getting in SOQL? Please make sure you are looking in the same org where the issue is coming up. If you have a doubt you can change the API of the class to Latest, Is anything stopping you doing that?

 
Tripti Nirmal GuptaTripti Nirmal Gupta
Thanks Abdul,
public static final Id STANDARD_PRICEBOOK_ID = Test.isRunningTest() ?  Test.getStandardPricebookId() : [SELECT Id From Pricebook2 WHERE IsStandard = true].Id ;  

fixed the issue.
Abdul KhatriAbdul Khatri
Good to know that.