+ Start a Discussion
Turner GauTurner Gau 

Advanced Apex Specialist Superbadge - Step 7 - Ensure that the page works for existing Order records

Hi Gang,

Been trying all sorts of things to figure out anymore details for this error message that appears when I check the challenge on step 7, but coming up short.  Has anyone else experienced this error and any tips to resolve?

Challenge Not yet complete... here's what's wrong:
Ensure that the page works for existing Order records.

I have overridden both the New and Edit buttons/actions on the Order object.  My OrderExtension class appears to be working correctly in that I can successfully add new orders and edit them using the OrderEdit override vf page.  (The instructions specifically say not to edit that vf page so I have left it as is).  

In the log I see this is where it fails the check:
FATAL_ERROR AnonymousBlock: line 18, column 1
But unfortunately there are no real additional details that I see.

Any advice to resolve this or any tip to see more error information would be appreciated. 

Thanks!
Best Answer chosen by Turner Gau
Zachery EngmanZachery Engman
Verify your code works with the test it is doing, if not you will need to adjust to it.  It is very peticular:
Account testAccount = new Account();
testAccount.Name = 'test';
insert testAccount;
 
 orderExtension ext = new orderExtension(new apexPages.standardController(new Order()));
 ext.orderRecord.AccountId = testAccount.Id;
 ext.orderRecord.EffectiveDate = system.today();
 ext.orderRecord.Status = constants.DRAFT_ORDER_STATUS;
 ext.orderRecord.Pricebook2Id = constants.STANDARD_PRICEBOOK_ID;
 ext.orderItemList[0].Quantity = 1;
 ext.orderItemList[0].UnitPrice = 1;
 ext.orderItemList[1].Quantity = 2;
 ext.orderItemList[1].UnitPrice = 2;
 ext.save();
 
 List<Order> savedOrders = [SELECT Id, (SELECT Quantity, UnitPrice FROM OrderItems ORDER BY Quantity) FROM Order WHERE AccountId = :testAccount.Id];
 system.assert( savedOrders.size() == 1 );
 system.assert( savedOrders[0].OrderItems.size() == 2 );

 

All Answers

Zibing WangZibing Wang
Hi Turner,

Make sure you have the code to delete the OrderItem in your save function when the Quantity changed to 0. This should solve the problem. 
 
Turner GauTurner Gau
Thanks for the suggestion Zlblng, I did have the delete properly wired up as well.  Everything seems to function correctly in my manual tests.
Zachery EngmanZachery Engman
Verify your code works with the test it is doing, if not you will need to adjust to it.  It is very peticular:
Account testAccount = new Account();
testAccount.Name = 'test';
insert testAccount;
 
 orderExtension ext = new orderExtension(new apexPages.standardController(new Order()));
 ext.orderRecord.AccountId = testAccount.Id;
 ext.orderRecord.EffectiveDate = system.today();
 ext.orderRecord.Status = constants.DRAFT_ORDER_STATUS;
 ext.orderRecord.Pricebook2Id = constants.STANDARD_PRICEBOOK_ID;
 ext.orderItemList[0].Quantity = 1;
 ext.orderItemList[0].UnitPrice = 1;
 ext.orderItemList[1].Quantity = 2;
 ext.orderItemList[1].UnitPrice = 2;
 ext.save();
 
 List<Order> savedOrders = [SELECT Id, (SELECT Quantity, UnitPrice FROM OrderItems ORDER BY Quantity) FROM Order WHERE AccountId = :testAccount.Id];
 system.assert( savedOrders.size() == 1 );
 system.assert( savedOrders[0].OrderItems.size() == 2 );

 
This was selected as the best answer
AMIT SINGH 2375AMIT SINGH 2375
Hi Turner,

Can you please share the VF and Apex class with me? for Challenge #7
Shiva SFDeveloperShiva SFDeveloper
Just sharing so that it might help someone who may have done it in a similar way.
I was experiencing this issue earlier. I defined another method
public void updateOrderItemMap() {

}
that updates the "orderItemMap" map variable to add items for which quantity is changed to a value more than 0 and remove items whose quantity is updated to 0. In a regular page flow, the map will always be updated with recent orderitems data; and accordingly deletes items that are not part of the map. However, the challenge expects the save() method to explictly update the map and delete the items when called independently and out of the page flow; which I realized after spending quite some time. Just added my method call as the first statement in the save() method and that completed Step7 challenge.
ravi reddy 68ravi reddy 68
Hi Shiva, 
I have issues clearing challenge 8.Therr is something. Issuing in orderextension unit test  method.   Could you share your order tests class to cross-check where I am making mistake? 
AMIT SINGH 2375AMIT SINGH 2375
@isTest 
private class Product2Tests {

    /**
     * @name product2Extension_UnitTest
     * @description UnitTest for product2Extension
    **/
    static TestMethod void Product2Extension_UnitTest(){
    
        PageReference pageRef = Page.Product2New;
        Test.setCurrentPage(pageRef);
        
        List<Schema.PicklistEntry> familyEntries = Constants.PRODUCT_FAMILY;
        Integer familySize = familyEntries.size();
        
        ApexPages.StandardController stdController = new ApexPages.StandardController(new product2());
            Test.startTest();
                Product2Extension ext = new Product2Extension(stdController);
                
                System.assertEquals(ext.productsToInsert.size(), Constants.DEFAULT_ROWS);
                ext.addRows();
                System.assertEquals(ext.productsToInsert.size(), 2*Constants.DEFAULT_ROWS);
                
                for(Integer I=0; I < Constants.DEFAULT_ROWS; I++){
                    ext.productsToInsert[i].productRecord.Name = 'test Product' +I;
                    ext.productsToInsert[i].productRecord.IsActive = true;
                    ext.productsToInsert[i].productRecord.Initial_Inventory__c = 100;
                    ext.productsToInsert[i].productRecord.Family = familyEntries[(familySize - 1) - Math.mod(i, familySize)].value;
                    ext.productsToInsert[i].pricebookEntryRecord.UnitPrice = 30;
                }
                
                ext.save();
                List<Product2> prodList = [Select Id, Name From Product2 ];
                System.assertEquals(Constants.DEFAULT_ROWS , prodList.size());
                
                ext.GetFamilyOptions();
                
                ext.GetInventory();
                
            Test.stopTest();
    }
    
    public static TestMethod void Product2Trigger_UnitTest(){
         Integer productCount = [SELECT Count() FROM Product2];
         Integer pricebookCount = [SELECT Count() FROM PricebookEntry];
         PageReference pageRef = Page.Product2New;
         Test.setCurrentPage(pageRef);
         product2Extension ext = new product2Extension(new apexPages.standardController(new Product2()));
         ext.addRows();
         ext.addRows();
         ext.productsToInsert[0].productRecord.Name = 'TestTestTest';
         ext.productsToInsert[0].productRecord.Family = 'Entree';
         ext.productsToInsert[0].pricebookEntryRecord.UnitPrice = 1;
         ext.productsToInsert[0].pricebookEntryRecord.IsActive = true;
         ext.productsToInsert[0].productRecord.Initial_Inventory__c = 10;
         ext.save();
         
         system.assert( productCount+1 == [SELECT Count() FROM Product2] );
         system.assert( pricebookCount+1 == [SELECT Count() FROM PricebookEntry]);
         
         delete [SELECT Id FROM Product2 WHERE Name = 'TestTestTest'];
    }

}

 
ravi reddy 68ravi reddy 68
@shailendra
 thanks for the reply.I am working on OrderExtension_UnitTest in OrderTests that tests all the methods in the OrderExtension class. The above code is related to Product2extension test .If you could  share orderextension unit test  ?
ravi reddy 68ravi reddy 68
Hi make sure you have 15 or less than 15 products in your org.if there is more than 15 , delete them manually.
ravi reddy 68ravi reddy 68
Hi Check "view raw logs" and see what could be the problem.
ravi reddy 68ravi reddy 68
Hi See if it is returning getTotalPages as expected from "rawlogs"?.
ravi reddy 68ravi reddy 68
Hi There is last section of raw logs where you can see test results. make sure you check last section which is not there in above code.
ravi reddy 68ravi reddy 68
Hi Scroll down to last section of rawlogs and you will see the assertions
ravi reddy 68ravi reddy 68
I have this save method implemented. you can crosscheck with this. public void Save(){ //ToDo: Implement logic to save the Order and populated OrderItems System.Savepoint sp = Database.setSavepoint(); try { if (null == orderRecord.Pricebook2Id) { orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID; } upsert orderRecord; List orderItemsToUpsert = new List(); List orderItemsToDelete = new List(); for (OrderItem oi : orderItemList) { if (oi.Quantity > 0) { if (null == oi.OrderId) { oi.OrderId = orderRecord.Id; } orderItemsToUpsert.add(oi); } else if (oi.Id != null) { orderItemsToDelete.add(oi); } } upsert orderItemsToUpsert; delete orderItemsToDelete; } catch (Exception e) { Database.rollback(sp); apexPages.addMessage(new ApexPages.message( ApexPages.Severity.INFO,Constants.ERROR_MESSAGE)); } }
ravi reddy 68ravi reddy 68
Hi Check if you have order VF page is displayed when you click new or add button in your org.else make sure you override buttons.
ravi reddy 68ravi reddy 68
And see if you are able to do it manually with set controller methods on VF page. On Dec 25, 2017 9:57 AM, "Ravinder Kongara" wrote: Hi Check if you have order VF page is displayed when you click new or add button in your org.else make sure you override buttons.
ravi reddy 68ravi reddy 68
When you click new or add button, make sure you have set controller buttons available and see if they are working as expected by showing how many pages or how many products.if not, make sure you add them to page layout of order
ravi reddy 68ravi reddy 68
Great. Good to know you passed challenge.
Nirmallya_GhoshNirmallya_Ghosh
I am also getting the same error
Nirmallya_GhoshNirmallya_Ghosh

@veeranjaneyulu kunchala 9

Did you able to pass the challange ?
 

Nirmallya_GhoshNirmallya_Ghosh
Below is My Code.... What i am doing wrong please let me know - 

/**
 * @name OrderExtension
 * @description This class is provided for you to facilitate the Super Badge
**/
public class OrderExtension {

    public Order orderRecord {get;set;}
    public List<OrderItem> orderItemList {get;set;}
    public String selectedFamily {get;set;}
    public List<chartHelper.chartData> pieData {get;set;}
    public Decimal total {get;set;}

    public Map<Id,OrderItem> orderItemMap;
    public ApexPages.StandardSetController standardSetController;

    /*
    public OrderExtension(ApexPages.StandardSetController standardSetController){
  
    }
    */
    
    public OrderExtension(ApexPages.StandardController standardController){
        if(standardController == null){
          standardSetController = new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Product2Id, Product2.Family, Product2.Name, Product2.Quantity_Remaining__c, UnitPrice FROM PricebookEntry]));
          standardSetController.setPageSize(Constants.DEFAULT_ROWS);
        }
        orderRecord = (Order)standardController.getRecord();
        orderItemMap = new Map<id,OrderItem>();
        if ( orderRecord.Id != null ){
            orderRecord = queryOrderRecord(orderRecord.Id);
        }

        resetSsc();
        total = 0;

        for (OrderItem oi : orderRecord.OrderItems) {
            orderItemMap.put(oi.Product2Id, oi);
            if (oi.Quantity > 0) {
                if (null == pieData) {
                    pieData = new List<ChartHelper.ChartData>();
                }
                pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
                total += oi.UnitPrice * oi.Quantity;
            }
        }
        GetOrderItems();
    }

    public void resetSsc() {
        String query = 'SELECT Name, Product2.Family, Product2.Name, Product2Id, UnitPrice, Product2.Quantity_Remaining__c'
                     + '  FROM PricebookEntry WHERE IsActive = TRUE';

        if (selectedFamily != null && selectedFamily != Constants.SELECT_ONE) {
            query += ' AND Product2.Family = \'' + selectedFamily + '\'';
        }
        query += ' ORDER BY Name';

        standardSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
        standardSetController.setPageSize(Constants.DEFAULT_ROWS);
    }

    //ToDo: Implement your own method to populate orderItemList
    //  that you will call after pagination and/or family selection
    public void GetOrderItems() {
        orderItemList = new List<OrderItem>();
        for (SObject obj : standardSetController.getRecords()) {
            PricebookEntry pbe = (PricebookEntry)obj;
            if (orderItemMap.containsKey(pbe.Product2Id)) {
                orderItemList.add(orderItemMap.get(pbe.Product2Id));
            } else {
                orderItemList.add(new OrderItem(
                    PricebookEntryId=pbe.Id,
                    Product2Id=pbe.Product2Id,
                    UnitPrice=pbe.UnitPrice,
                    Quantity=0,
                    Product2=pbe.Product2
                ));
            }
        }
    }


    /**
     * @name OnFieldChange
     * @description
    **/
    public void onFieldChange(){
        //ToDo: Implement logic to store the values changed on the page
        for (OrderItem oi : orderItemList) {
            orderItemMap.put(oi.Product2Id, oi);
        }

        //      and populate pieData
        pieData = null;
        total = 0;
        //for (OrderItem oi : orderItemList) {
        for (OrderItem oi : orderItemMap.values()) {
            if (oi.Quantity > 0) {
                if (null == pieData) {
                    pieData = new List<chartHelper.ChartData>();
                }
                pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
                //      and populate total
                total += oi.UnitPrice * oi.Quantity;
            }
        }
    }

    /**
     * @name SelectFamily
     * @description
    **/
    public void SelectFamily(){
        //ToDo: Implement logic to filter based on the selected product family
        resetSsc();
        GetOrderItems();
    }

    /**
     * @name Save
     * @description
    **/
    public void Save(){
        //ToDo: Implement logic to save the Order and populated OrderItems
        System.Savepoint sp = Database.setSavepoint();
        try {
            if (null == orderRecord.Pricebook2Id) {
                orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
            }
            upsert orderRecord;

            List<OrderItem> orderItemsToUpsert = new List<OrderItem>();
            List<OrderItem> orderItemsToDelete = new List<OrderItem>();
            //for (OrderItem oi : orderItemList) {
            for (OrderItem oi : orderItemMap.values()) {
                if (oi.Quantity > 0) {
                    if (null == oi.OrderId) {
                        oi.OrderId = orderRecord.Id;
                    }
                    orderItemsToUpsert.add(oi);
                } else if (oi.Id != null) {
                    orderItemsToDelete.add(oi);
                }
            }
            upsert orderItemsToUpsert;
            delete orderItemsToDelete;
        } catch (Exception e) {
            Database.rollback(sp);
            apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,Constants.ERROR_MESSAGE));
        }
    }


    /**
     * @name First
     * @description
    **/
    public void First(){
        this.standardSetController.first();
        GetOrderItems();
    }


    /**
     * @name Next
     * @description
    **/
    public void Next(){
        this.standardSetController.next();
        GetOrderItems();
    }


    /**
     * @name Previous
     * @description
    **/
    public void Previous(){
        this.standardSetController.previous();
        GetOrderItems();
    }

    /**
     * @name Last
     * @description
    **/
    public void Last(){
        this.standardSetController.last();
        GetOrderItems();
    }

    /**
     * @name GetHasPrevious
     * @description
    **/
    public Boolean GetHasPrevious(){
        return standardSetController.getHasPrevious();
    }

    /**
     * @name GetHasNext
     * @description
    **/
    public Boolean GetHasNext(){
        return standardSetController.getHasNext();
    }

    /**
     * @name GetTotalPages
     * @description
    **/
    public Integer GetTotalPages(){
        return (Integer)Math.ceil(standardSetController.getResultSize() / (Decimal)Constants.DEFAULT_ROWS);
    }

    /**
     * @name GetPageNumber
     * @description
    **/
    public Integer GetPageNumber(){
        return standardSetController.getPageNumber();
    }

    /**
     * @name GetFamilyOptions
     * @description
    **/
    public List<SelectOption> GetFamilyOptions() {
        List<SelectOption> options = new List<SelectOption>{
            new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE)
        };

        for (Schema.PicklistEntry ple : Constants.PRODUCT_FAMILY) {
            options.add(new SelectOption(ple.getValue(), ple.getLabel()));
        }
        return options;
    }

    /**
     * @name QueryOrderRecord
     * @description
    **/
    public static Order QueryOrderRecord(Id orderId){
        return [
            SELECT Id, AccountId, EffectiveDate, Name, Status, Pricebook2Id,
                (
                    SELECT Id, OrderId, Quantity, UnitPrice, PricebookEntryId, Product2Id,
                         Product2.Name, Product2.Family, Product2.Quantity_Remaining__c
                    FROM OrderItems
                )
            FROM Order
            WHERE Id = :orderId
        ];
    }

}

 
ANKUR GUPTA 63ANKUR GUPTA 63
At Step 7 :  I am getting : 
Challenge Not yet complete... here's what's wrong: 
Ensure that values are preserved during pagination.

Can someone help ?
ANKUR GUPTA 63ANKUR GUPTA 63
@Nirmallya_Ghosh:
Have tried with using 'this' -- 
this.standardSetController.previous()  --->standardSetController.previous()
Nirmallya_GhoshNirmallya_Ghosh
Not working boss
 
Siddharth SethSiddharth Seth
@Nirmallya_Ghosh what error are you getting?
Paras PrajapatiParas Prajapati
@ Nirmallya_Ghosh
    Do not use below line in your code :
            for (OrderItem oi : orderItemMap.values()) {

   Use below line for the above for loop, if you have not passed the challenged still
           for(OrderItem  oi : orderItemList){
   This will resolve the issue.
 
anusha reddy9anusha reddy9
@Ravi reddy 68

I completed the Advanced Apex Specialist Superbadge Step - 1 and now stuck in the Advanced Apex Specialist Superbadge Step - 2
Can you please help me to solve the puzzle..Spent 5hours still not able to solve the challenge. 
My email id is anusha.rkm@gmail.com..Thankyou in advance:-)
Amit Singh 1Amit Singh 1
Hi Anusha,

What is the Error you are getting and in step 2 what is the challenge?

Regards,
Amit
ravi reddy 68ravi reddy 68
@Anusha, What was the error ?. Or You could try checking step3 and step4 and so on on the forum to see if anybody had the same issue as yours.I am sure you can find the answer for step 2 in other questions.
Amit Singh 1Amit Singh 1
If you are looking for Order Trigger and Order Helper Code then find below
/**
 * @name orderTrigger
 * @description
**/
trigger orderTrigger on Order (after update) {
    OrderHelper.AfterUpdate(Trigger.New, Trigger.Old);
}
public without sharing class OrderHelper {
    /**
        * @name AfterUpdate
        * @description 
        * @param List<Order> newList
        * @param List<Order> oldList
        * @return void
    **/
    public static void AfterUpdate(List<Order> newList, List<Order> oldList){
        Set<Id> orderIds = new Set<Id>();
        for ( Integer i=0; i< newList.size(); i++ ){
            if ( newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && oldList[i].Status == Constants.DRAFT_ORDER_STATUS ){
                orderIds.add(newList[i].Id);
            }
        }
        RollUpOrderItems(orderIds);
    }
    
    /**
        * @name RollUpOrderItems
        * @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
        * @param Set<Id> activatedOrderIds
        * @return void
    **/
    public static void RollUpOrderItems(Set<Id> activatedOrderIds){
        //ToDo: Declare a Map named "productMap" of Ids to Product2 records
        Map<Id, Product2> productMap = new Map<Id, Product2>(); 
        for(OrderItem orderLine : [SELECT Id, Product2Id, Product2.Quantity_Ordered__c, Quantity, Order.ActivatedDate
                                   FROM OrderItem WHERE OrderId IN : activatedOrderIds]){ 
                                  if(!productMap.containsKey(orderLine.Product2Id))
                                      productMap.put(orderLine.Product2Id, new Product2(Id =orderLine.Product2Id, Quantity_Ordered__c=0)); 
        }
        
        for(AggregateResult ag : [SELECT Sum(Quantity), Product2Id FROM OrderItem WHERE Product2Id IN : productMap.keySet() Group By Product2Id]){
            Id product2Id = (Id)ag.get('Product2Id');
            Product2 prod = productMap.get(product2Id);
            prod.Quantity_Ordered__c = (Decimal)ag.get('expr0');
            productMap.put(product2Id , prod);
        }
        
        
        try { 
            if(productMap.values() != null && productMap.values().size() > 0){ 
                update productMap.values(); 
            } 
        }catch ( Exception e ){ 
            System.debug('#### Exception Executed : '+e.getStackTraceString()); 
        } 
    }
    
}


 
Yashita Goyal 17Yashita Goyal 17
Am facing issue on Step 8.

Can you please share OrderTests and TestDataFactory class?
Amit Singh 1Amit Singh 1
Yeah Sure,

TestDataFactory
/**
 * @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 collaborationGroup = new CollaborationGroup();
        collaborationGroup.Name = 'TEST' + Constants.INVENTORY_ANNOUNCEMENTS;
        collaborationGroup.CollaborationType = 'Public';
        //insert collaborationGroup;
        return collaborationGroup;
    }

    /**
     * @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> productsList = new List<Product2>();
        List<Schema.PicklistEntry> familyEntries = Constants.PRODUCT_FAMILY;
        Integer familySize = familyEntries.size();
        for (Integer i = 0; i < cnt; i++) {
            Product2 prd = new Product2();
            prd.Name = 'Product ' + i;
            prd.isActive = true;
            prd.Initial_Inventory__c = 10;
            prd.Family = familyEntries[(familySize - 1) - Math.mod(i, familySize)].value;
            productsList.add(prd);
        }
        //insert productsList;
        return productsList;
    }

    /**
     * @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
        Id pricebookId = Constants.STANDARD_PRICEBOOK_ID;
        List<PricebookEntry> pricebookEntries = new List<PricebookEntry>();
        for (Product2 prd : prods) {
            PricebookEntry standardPrice = new PricebookEntry(
                    Pricebook2Id = pricebookId, Product2Id = prd.Id,
                    UnitPrice = 10000, IsActive = true);
            pricebookEntries.add(standardPrice);
        }
        //insert pricebookEntries;
        return pricebookEntries;
    }

    /**
     * @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> accounts = new List<Account>();
        for (Integer i = 0; i < cnt; i++) {
            Account acc = new Account(Name = 'TEST ' + i);
            accounts.add(acc);
        }
        //insert accounts;
        return accounts;
    }

    /**
     * @name CreateContacts
     * @description Constructs a list of Contacxt 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.
        System.debug(LoggingLevel.ERROR,accts);
        List<Contact> contacts = new List<Contact>();
        Integer accountsSize = accts.size();
        //(accountsSize - 1) - Math.mod(i, accountsSize)
        for (Integer i = 0; i < cnt; i++) {
            //System.debug(LoggingLevel.ERROR,(accountsSize - 1) - Math.mod(i, accountsSize));
            Contact con = new Contact(FirstName = 'FirstName', LastName = 'TEST ' + i, AccountId = accts[i].Id);
            contacts.add(con);
        }
        //insert contacts;
        return contacts;
    }

    /**
     * @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> ordersList = new List<Order>();
        Integer accountsSize = accts.size();
        for (Integer i = 0; i < cnt; i++) {
            Order ord = new Order(AccountId = accts[i].Id, EffectiveDate = Date.today() + i, Status = 'Draft', Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID);//(accountsSize - 1) - Math.mod(i, accountsSize)
            ordersList.add(ord);
        }
        //insert ordersList;
        return ordersList;
    }

    /**
     * @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
        //(ordersSize - 1) - Math.mod(i, ordersSize)
        //(pbeSize - 1) - Math.mod(i, pbeSize)
        List<OrderItem> orderItems = new List<OrderItem>();
        Integer ordersSize = ords.size();
        Integer pbeSize = pbes.size();
        for (Integer i = 0; i < cnt; i++) {
            OrderItem oi = new OrderItem(OrderId = ords[i].Id, Quantity = Constants.DEFAULT_ROWS, UnitPrice = 25, PricebookEntryId = pbes[i].Id);
            orderItems.add(oi);
        }
        //insert orderItems;
        return orderItems;
    }

    /**
     * @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 collaborationGroup = constructCollaborationGroup();
        insert collaborationGroup;
        List<Product2> productsList = constructProducts(cnt);
        insert productsList;
        List<PricebookEntry> ConstructPricebookEntries = constructPricebookEntries(productsList);
        insert ConstructPricebookEntries;
        List<Account> ConstructAccounts = constructAccounts(cnt);
        insert ConstructAccounts;
        List<Contact> ConstructContacts = constructContacts(cnt, ConstructAccounts);
        insert ConstructContacts;
        List<Order> ConstructOrders = constructOrders(cnt, ConstructAccounts);
        insert ConstructOrders;
        List<OrderItem> ConstructOrderItems = constructOrderItems(cnt, ConstructPricebookEntries, ConstructOrders);
        insert ConstructOrderItems;
    }

    public static void VerifyQuantityOrdered(Product2 originalProduct, Product2 updatedProduct, Integer qtyOrdered) {
        System.assertEquals(originalProduct.Quantity_Ordered__c + qtyOrdered, updatedProduct.Quantity_Ordered__c);
    }
    public static void setupTestData() {
        TestDataFactory.insertTestData(Constants.DEFAULT_ROWS);
    }

}

OrderTests
@isTest 
private class OrderTests {
    @testSetup
    public static void SetupTestData(){
        TestDataFactory.insertTestData(10);
    }
    
    public static testMethod void OrderUpdate_UnitTest(){
        List<Order> orderList = new List<Order>();
        orderList = [Select Id, Name, Status From Order Limit 1000];
        List<Product2> originalProduct = [Select Id, Name, Initial_Inventory__c, Quantity_Ordered__c From Product2 Limit 1000];
        System.debug('#### orderList  '+orderList );
        for(Order ord : orderList){
            ord.Status = Constants.ACTIVATED_ORDER_STATUS;
        }
        update orderList;
        List<Product2> updatedProduct = [Select Id, Name, Initial_Inventory__c, Quantity_Ordered__c From Product2 Limit 1000];
        for(Integer I =0; I < originalProduct.size(); I++ ){
            TestDataFactory.VerifyQuantityOrdered(originalProduct[i], updatedProduct[i], Constants.DEFAULT_ROWS);
        }
    }
    public static testMethod void OrderExtension_UnitTest(){
        Account testAccount = new Account();
        testAccount.Name = 'test';
        insert testAccount;
        
        List<Schema.PicklistEntry> familyEntries = Constants.PRODUCT_FAMILY;
        Integer familySize = familyEntries.size();
        
         List<Account> ConstructAccounts = TestDataFactory.constructAccounts(Constants.DEFAULT_ROWS);
        insert ConstructAccounts;
        // Insert Order
        List<Order> ConstructOrders = TestDataFactory.constructOrders(Constants.DEFAULT_ROWS, ConstructAccounts);
        insert ConstructOrders;
        
        List<Product2> productList = new List<product2>();
        // Insert Product 
        List<Product2> productsList = TestDataFactory.constructProducts(Constants.DEFAULT_ROWS);
        insert productsList;
        
        List<PricebookEntry> ConstructPricebookEntries = TestDataFactory.constructPricebookEntries(productsList);
        insert ConstructPricebookEntries;
        
        List<OrderItem> ConstructOrderItems = TestDataFactory.constructOrderItems(Constants.DEFAULT_ROWS, ConstructPricebookEntries, ConstructOrders);
        insert ConstructOrderItems;

        orderExtension ext = new orderExtension(new apexPages.standardController(ConstructOrders[0]));
        ext.orderRecord.AccountId = testAccount.Id;
        ext.orderRecord.EffectiveDate = system.today();
        ext.orderRecord.Status = constants.DRAFT_ORDER_STATUS;
        ext.orderRecord.Pricebook2Id = constants.STANDARD_PRICEBOOK_ID;
        ext.orderItemList[0].Quantity = 1;
        ext.orderItemList[0].UnitPrice = 1;
        ext.orderItemList[1].Quantity = 2;
        ext.orderItemList[1].UnitPrice = 2;
        ext.save();
        
        List<Order> savedOrders = [SELECT Id, (SELECT Quantity, UnitPrice FROM OrderItems ORDER BY Quantity) FROM Order WHERE AccountId = :testAccount.Id];
        system.assert( savedOrders.size() == 1 );
        system.assert( savedOrders[0].OrderItems.size() == 2 );
        
        ext.GetFamilyOptions();
        ext.selectedFamily =  familyEntries[(familySize - 1) - Math.mod(1, familySize)].value;
        ext.SelectFamily();
        ext.orderItemList[0].Quantity = 10;
        ext.OnFieldChange();
        ext.First();
        ext.Next();
        ext.Previous();
        ext.Last();
        ext.GetHasPrevious();
        ext.GetHasNext();
        ext.GetTotalPages();
        ext.GetPageNumber();
    }

}

 
Yashita Goyal 17Yashita Goyal 17
Am getting this error:
Ensure that you haven't deleted the product2Trigger_UnitTest in orderTests.
Amit Singh 1Amit Singh 1
Add Below method into OrderTests class
public static TestMethod void Product2Trigger_UnitTest(){
         Integer productCount = [SELECT Count() FROM Product2];
         Integer pricebookCount = [SELECT Count() FROM PricebookEntry];
         PageReference pageRef = Page.Product2New;
         Test.setCurrentPage(pageRef);
         product2Extension ext = new product2Extension(new apexPages.standardController(new Product2()));
         ext.addRows();
         ext.addRows();
         ext.productsToInsert[0].productRecord.Name = 'TestTestTest';
         ext.productsToInsert[0].productRecord.Family = 'Entree';
         ext.productsToInsert[0].pricebookEntryRecord.UnitPrice = 1;
         ext.productsToInsert[0].pricebookEntryRecord.IsActive = true;
         ext.productsToInsert[0].productRecord.Initial_Inventory__c = 10;
         ext.save();
         
         system.assert( productCount+1 == [SELECT Count() FROM Product2] );
         system.assert( pricebookCount+1 == [SELECT Count() FROM PricebookEntry]);
         
         delete [SELECT Id FROM Product2 WHERE Name = 'TestTestTest'];
    }

 
Yashita Goyal 17Yashita Goyal 17
I added that already from Product2Test class. My Product2Helper is just 60% covered.

Here is my code Product2Tests class:
@isTest 
private class Product2Tests {

    /**
     * @name product2Extension_UnitTest
     * @description UnitTest for product2Extension
    **/
    static TestMethod void Product2Extension_UnitTest(){
    
        PageReference pageRef = Page.Product2New;
        Test.setCurrentPage(pageRef);
        
        List<Schema.PicklistEntry> familyEntries = Constants.PRODUCT_FAMILY;
        Integer familySize = familyEntries.size();
        
        ApexPages.StandardController stdController = new ApexPages.StandardController(new product2());
            Test.startTest();
                Product2Extension ext = new Product2Extension(stdController);
                
                System.assertEquals(ext.productsToInsert.size(), Constants.DEFAULT_ROWS);
                ext.addRows();
                System.assertEquals(ext.productsToInsert.size(), 2*Constants.DEFAULT_ROWS);
                
                for(Integer I=0; I < Constants.DEFAULT_ROWS; I++){
                    ext.productsToInsert[i].productRecord.Name = 'test Product' +I;
                    ext.productsToInsert[i].productRecord.IsActive = true;
                    ext.productsToInsert[i].productRecord.Initial_Inventory__c = 100;
                    ext.productsToInsert[i].productRecord.Family = familyEntries[(familySize - 1) - Math.mod(i, familySize)].value;
                    ext.productsToInsert[i].pricebookEntryRecord.UnitPrice = 30;
                }
                
                ext.save();
                List<Product2> prodList = [Select Id, Name From Product2 ];
                System.assertEquals(Constants.DEFAULT_ROWS , prodList.size());
                
                ext.GetFamilyOptions();
                
                ext.GetInventory();
                
            Test.stopTest();
    }
    
    public static TestMethod void Product2Trigger_UnitTest(){
         Integer productCount = [SELECT Count() FROM Product2];
         Integer pricebookCount = [SELECT Count() FROM PricebookEntry];
         PageReference pageRef = Page.Product2New;
         Test.setCurrentPage(pageRef);
         product2Extension ext = new product2Extension(new apexPages.standardController(new Product2()));
         ext.addRows();
         ext.addRows();
         ext.productsToInsert[0].productRecord.Name = 'TestTestTest';
         ext.productsToInsert[0].productRecord.Family = 'Entree';
         ext.productsToInsert[0].pricebookEntryRecord.UnitPrice = 1;
         ext.productsToInsert[0].pricebookEntryRecord.IsActive = true;
         ext.productsToInsert[0].productRecord.Initial_Inventory__c = 10;
         ext.save();
         
         system.assert( productCount+1 == [SELECT Count() FROM Product2] );
         system.assert( pricebookCount+1 == [SELECT Count() FROM PricebookEntry]);
         
         delete [SELECT Id FROM Product2 WHERE Name = 'TestTestTest'];
    }

}

 
Yashita Goyal 17Yashita Goyal 17
And AnnouncementQueueable is 41%  :-|
anusha reddy9anusha reddy9
@Amit Singh, Challenge Not yet complete... here's what's wrong: Ensure that the getInventory method is implemented properly.
anusha reddy9anusha reddy9
@Ravi Reddy Challenge Not yet complete... here's what's wrong: Ensure that the getInventory method is implemented properly.