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

Advanced Apex Specialist Superbadge - Step 5
I'm getting the following error on Advanced Apex Specialist Superbadge - Step 5. Any ideas please?

Here is the current code segments:
VerifyQuantityOrdered
Here is the current code segments:
VerifyQuantityOrdered
Public static void VerifyQuantityOrdered(Product2 originalProduct, Product2 updatedProduct, Integer qtyOrdered) { decimal tot = (originalProduct.Quantity_Ordered__c + qtyOrdered); system.debug('OldVQ ' + originalProduct.Quantity_Ordered__c); system.debug('NewVQ ' + updatedProduct.Quantity_Ordered__c); system.debug('QTYVQ ' + qtyOrdered); system.assertEquals(updatedProduct.Quantity_Ordered__c,tot); }OrderTests
@isTest private with sharing class OrderTests { @testSetup private static void SetupTestData (){ TestDataFactory.InsertTestData(5); } @isTest private static void OrderUpdate_UnitTest (){ Test.startTest(); List<Order> OrderList = [select id, name, status from order]; For (Order ordrec : OrderList) { OrderItem oirec = [select id, Pricebookentry.product2Id from orderitem where orderid=:ordrec.id]; Product2 oldprodrec = [SELECT Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 where id =: oirec.Pricebookentry.product2Id limit 1]; ordrec.status = constants.ACTIVATED_ORDER_STATUS; update ordrec; OrderItem oirec1 = [select id, Pricebookentry.product2Id from orderitem where orderid=:ordrec.id]; Product2 newprodrec = [SELECT Family,Id,Name,Quantity_Ordered__c,Quantity_Remaining__c FROM Product2 where id =: oirec1.Pricebookentry.product2Id limit 1]; system.debug('Old ' + oldprodrec.Quantity_Ordered__c); system.debug('New ' + newprodrec.Quantity_Ordered__c); system.debug('QTY ' + constants.DEFAULT_ROWS); TestDataFactory.VerifyQuantityOrdered(oldprodrec,newprodrec,constants.DEFAULT_ROWS); } Test.stopTest(); } }Product2Tests
@isTest (seeAllData=false) private with sharing class Product2Tests { /** * @name product2Extension_UnitTest * @description UnitTest for product2Extension **/ @isTest private static void Product2Extension_UnitTest(){ // Set-up user String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com'; Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; User u = new User(Alias = 'standt', Email='standarduser@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName=uniqueUserName); System.runAs(u) { // When a user first visits the page, there should be multiple rows displayed on the screen. // Assert that the size of the productsToInsert list is equal to the DEFAULT_ROWS constant. // Test.StartTest(); Product2 prod = new Product2(name='Test',isActive=true); ApexPages.StandardController stdc = new ApexPages.StandardController(prod); Product2Extension p2x = new Product2Extension(stdc); System.assertEquals(Constants.DEFAULT_ROWS, p2x.productsToInsert.size()); // Test.StopTest(); // When the Add button is clicked, an additional set of rows should be added, // so assert that the size of the productsToInsert ** list is double **DEFAULT_ROWS after the button is clicked once. // Test.StartTest(); p2x.addRows(); System.assertEquals(Constants.DEFAULT_ROWS * 2, p2x.productsToInsert.size()); // Test.StopTest(); // Next, test the Save button. Verify that populated rows are saved and unpopulated rows are not saved. // Loop through the rows in the productsToInsert list and populate the values of the first 5 records, // and then simulate clicking the Save button. Verify that the button worked by asserting that only 5 products were saved. integer x = 0; for (Product2Extension.ProductWrapper PTI : p2x.productsToInsert){ pti.productrecord.name='TESTPRODUCT ' + x; pti.productRecord.IsActive = true; pti.productRecord.Initial_Inventory__c = 20; pti.productRecord.Family = Constants.PRODUCT_FAMILY[0].getValue(); pti.pricebookEntryRecord.UnitPrice = 10; x++; if (x==5) {break;} } // Test.startTest(); p2x.save(); // Test.stopTest(); List<Product2> createdProducts = [SELECT Id FROM Product2]; System.assertEquals(5, createdProducts.size()); // plus some more test areas p2x.GetFamilyOptions(); p2x.GetInventory(); } } }
https://techevangel.com/2018/06/01/superbadge-advanced-apex-specialist/
Create the new VerifyQuantityOrdered method in TestDataFactory according to its signature. Update OrderTests to verify OrderTrigger and OrderHelper logic. Complete the Product2Extension_UnitTest in Product2Tests.
Add a new method VerifyQuantityOrdered with the mentioned signature in TestDataFactory.
System.assertEquals((updatedProduct.Quantity_Ordered__c – originalProduct.Quantity_Ordered__c), qtyOrdered);
Update the seeAllData annotation value to false
Create a test setup method SetupTestData which invoke InsertTestData method of TestDataFactory class
Create a new test method named OrderUpdate_UnitTest in OrderTests
Select a product before updating the order
Select an Order and update its status to Constants. ACTIVATED _ORDER _STATUS
Select the updated product
Pass the values into the VerifyQuantityOrdered method
Create or complete the Product2Extension_UnitTest in Product2Tests
Update the seeAllData annotation value to false
Create a StandardController instance of the Product2 object
Create a Product2Extension instance by passing StandardControlleras its constructor parameter
Check if the number of added rows equal to Constants.DEFAULT_ROWS – Use Assert Equal
Call the AddRows() method and do an Assert Equal once again
Insert few products and price book entries to productsToInsert
Invoke the method – Save()
Invoke the method – GetFamilyOptions()
Invoke the method – GetInventory()
Check if the Save action works as expected using Assert Equal
Other people have found this issue. It's to do with the assertions. Scrap the assertEquals tests and replace the System.assert.
Ensure that you create the OrderUpdate_UnitTest test method with the proper declaration and proper access modifier, to ensure best practices.
I've got stuck here as well. Looks like validator calls TestDataFactory.VerifyQuantityOrdered method with arguments:
originProduct2:{Quantity_Ordered__c=0} , updatedProduct2:{Quantity_Ordered__c=10} , 20. That's why we have System.AssertException: Assertion Failed: Expected: 10, Actual: 20. Any ideas how to resolve the issue. Any workarounds?
Private access modifier, and @isTest annotation rather than TestMethod keyword
@isTest private static void orderUpdate_UnitTest() {}
@isTest private static void orderExtension_UnitTest() {}
This has resolved the error of "Ensure that you create the OrderUpdate_UnitTest test method with the proper declaration and proper access modifier, to ensure best practices."
"Ensure that you create the OrderUpdate_UnitTest test method with the proper declaration and proper access modifier, to ensure best practices."
OrderTest class code-
@isTest
public class OrderTests {
@testSetup static void SetupTestData(){
TestDataFactory.InsertTestData(5);
}
@isTest private static void OrderUpdate_UnitTest() {
Test.startTest();
Order rec = [SELECT Id, Status FROM Order LIMIT 1];
Product2 prod = [SELECT Id, Family, Name, Quantity_Ordered__c, Quantity_Remaining__c FROM Product2 LIMIT 1];
rec.status = constants.ACTIVATED_ORDER_STATUS;
Update rec;
Product2 updatedprod = [SELECT Id, Family, Name, Quantity_Ordered__c, Quantity_Remaining__c FROM Product2 LIMIT 1];
TestDataFactory.VerifyQuantityOrdered(prod, updatedprod, constants.DEFAULT_ROWS);
Test.stopTest();
}
}
@isTest (seeAllData=false)
private class OrderTests{
@isTest private static void OrderUpdate_UnitTest(){}
}
Pay attention @isTest private static void for every test method.
I missed private and spent two days for the step.
Hi Mayur, I have realised if you only have test method 'OrderUpdate_UnitTest' in test class OrderTests with proper declaration and access modifier - You will still get same error as above and to solve it , you need both method in class 'OrderUpdate_UnitTest' and 'OrderExtension_UnitTest' and it will work . like @priyanka suggested above:
@isTest (seeAllData=false)
private class OrderTests {
@isTest private static void orderUpdate_UnitTest() {<insert your code>}
@isTest private static void orderExtension_UnitTest() {<insert your code>}
}
Added below code for OrderTest
@isTest (seeAllData=false)
private class OrderTests {
@testSetup
static void SetupTestData() {
TestDataFactory.InsertTestData(20);
}
@isTest private static void OrderUpdate_UnitTest() {
Order selectedOrder = [Select name,Status, Id from Order limit 1];
Product2 oldProd = [Select Quantity_Ordered__c, Name, Id from Product2 limit 1];
selectedOrder.Status = Constants.ACTIVATED_ORDER_STATUS;
update selectedOrder;
Product2 updatedProd = [Select Quantity_Ordered__c, Name, Id from Product2 limit 1];
TestDataFactory.VerifyQuantityOrdered(oldProd,updatedProd,Constants.DEFAULT_ROWS);
}
@isTest private static void OrderExtension_UnitTest() {
PageReference reference = Page.OrderEdit;
Test.setCurrentPage(reference);
Order CurOrder = [Select Id,Status from Order limit 1];
ApexPages.StandardController controller = new Apexpages.StandardController(CurOrder);
OrderExtension extension = new OrderExtension(controller);
System.assertEquals(5, extension.orderItemList.size());
extension.selectedFamily = 'Dessert';
extension.SelectFamily();
extension.OnFieldChange();
extension.First();
extension.Next();
extension.Previous();
extension.Last();
extension.GetHasNext();
extension.GetPageNumber();
extension.GetHasPrevious();
extension.GetTotalPages();
extension.GetFamilyOptions();
extension.Save();
ChartHelper.GetInventory();
}
}
Your solution really worked for me. Thanks....
inside sytem.runAs
Test.setCurrentPage(Page.Product2New);
Adding the following to Product2Extension_UnitTest() seemed to clear the error:
PageReference pageRef = page.Product2New;
Also take care of updating the assetEquals to assert() as below
can someone please help me ro resolve this error.
Challenge Not yet complete... here's what's wrong:
Ensure that you simulate a user visiting the product2New page by using the appropriate method in the System Test class.
Here is the code
/**
* @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 grp = new CollaborationGroup();
grp.Name='TEST'+Constants.INVENTORY_ANNOUNCEMENTS;
grp.CollaborationType='Public';
grp.IsAutoArchiveDisabled = true;
return grp;
}
/**
* @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> products = new List<Product2>();
for(Integer i = 1; i<=cnt ; i++){
Product2 prod = new Product2(Name='Product1'+i, Initial_Inventory__c = 10, isActive=true, family= Constants.PRODUCT_FAMILY.get(math.mod(i,4)).getValue());
products.add(prod);
}
return products;
}
/**
* @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> entries = new List<PriceBookEntry>();
for(Product2 prod : prods) {
PriceBookEntry entry = new PriceBookEntry();
entry.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
entry.Product2Id = prod.Id;
entry.UnitPrice = 100;
entry.IsActive = true;
entries.add(entry);
}
return entries;
}
/**
* @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> testAcc = new List<Account>();
for(Integer i=1;i<=cnt;i++){
testAcc.add(new Account(Name='TEST_ACCOUNT_'+i));
}
return testAcc;
}
/**
* @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.
List<Contact> contacts = new List<Contact>();
for(Integer i=0; i<cnt;i++) {
Integer index = Math.mod(i, accts.size());
Contact con = new Contact();
con.LastName = 'TestContact1'+i;
con.AccountId = accts.get(index).Id;
contacts.add(con);
}
System.debug('contacts size' + contacts.size());
System.debug('accts size' + accts.size());
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> orders = new List<Order>();
for (Integer i=0; i <cnt ; i++) {
Order ord = new Order();
ord.AccountId = accts.get(math.mod(i, accts.size())).Id;
ord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
ord.Status='Draft';
ord.EffectiveDate = System.today();
orders.add(ord);
}
return orders;
}
/**
* @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> items = new List<OrderItem>();
for(Integer i = 0; i <cnt; i++) {
OrderItem ord = new OrderItem();
ord.PricebookEntryId = pbes.get(math.mod(i, pbes.size())).Id;
ord.OrderId = ords.get(math.mod(i, ords.size())).Id;
ord.Quantity = Constants.DEFAULT_ROWS;
ord.UnitPrice = 250;
items.add(ord);
}
return items;
}
/**
* @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 groups = TestDataFactory.ConstructCollaborationGroup();
insert groups;
List<Product2> products= TestDataFactory.ConstructProducts(cnt);
insert products;
List<PriceBookEntry> entries = TestDataFactory.ConstructPricebookEntries(products);
insert entries;
List<Account> accts = TestDataFactory.ConstructAccounts(cnt);
insert accts;
List<Contact> contacts = TestDataFactory.ConstructContacts(cnt,accts);
insert contacts;
List<Order> orders = TestDataFactory.ConstructOrders( cnt, accts);
insert orders;
List<OrderItem> items = TestDataFactory.ConstructOrderItems(cnt, entries, orders);
insert items;
}
Public static void VerifyQuantityOrdered(Product2 originalProduct, Product2 updatedProduct, Integer qtyOrdered) {
decimal tot = (originalProduct.Quantity_Ordered__c + qtyOrdered);
system.debug('OldVQ ' + originalProduct.Quantity_Ordered__c);
system.debug('NewVQ ' + updatedProduct.Quantity_Ordered__c);
system.debug('QTYVQ ' + qtyOrdered);
system.assertEquals(updatedProduct.Quantity_Ordered__c,tot);
}
}
@isTest (seeAllData=false)
private with sharing class Product2Tests {
/**
* @name product2Extension_UnitTest
* @description UnitTest for product2Extension
**/
@isTest
private static void Product2Extension_UnitTest(){
// Set-up user
String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName=uniqueUserName);
System.runAs(u) {
// When a user first visits the page, there should be multiple rows displayed on the screen.
// Assert that the size of the productsToInsert list is equal to the DEFAULT_ROWS constant.
// Test.StartTest();
Product2 prod = new Product2(name='Test',isActive=true);
ApexPages.StandardController stdc = new ApexPages.StandardController(prod);
Product2Extension p2x = new Product2Extension(stdc);
System.assert(p2x.productsToInsert.size() == Constants.DEFAULT_ROWS);
// Test.StopTest();
// When the Add button is clicked, an additional set of rows should be added,
// so assert that the size of the productsToInsert ** list is double **DEFAULT_ROWS after the button is clicked once.
// Test.StartTest();
p2x.addRows();
System.assert(p2x.productsToInsert.size() == Constants.DEFAULT_ROWS * 2);
// Test.StopTest();
// Next, test the Save button. Verify that populated rows are saved and unpopulated rows are not saved.
// Loop through the rows in the productsToInsert list and populate the values of the first 5 records,
// and then simulate clicking the Save button. Verify that the button worked by asserting that only 5 products were saved.
integer x = 0;
for (Product2Extension.ProductWrapper PTI : p2x.productsToInsert){
pti.productrecord.name='TESTPRODUCT ' + x;
pti.productRecord.IsActive = true;
pti.productRecord.Initial_Inventory__c = 20;
pti.productRecord.Family = Constants.PRODUCT_FAMILY[0].getValue();
pti.pricebookEntryRecord.UnitPrice = 10;
x++; if (x==5) {break;}
}
// Test.startTest();
p2x.save();
// Test.stopTest();
List<Product2> createdProducts = [SELECT Id FROM Product2];
System.assertEquals(5, createdProducts.size());
// plus some more test areas
p2x.GetFamilyOptions();
p2x.GetInventory();
}
}
}