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

Help in Writing a Test Class please
Hi,
I have got a trigger that is as follows
I have written a test class but the trigger is still showing 0% coverage.
I am unable to post the class here as it is too long.
Can anyone please help me with the test class?
Thanks
I have got a trigger that is as follows
- trigger UpdateTargets on Monthly_Target__c (before Insert,before update) {
- set<id> AMids=new set<id>();
- for(Monthly_Target__c tg:trigger.new)
- {
- AMids.add(tg.Monthly_Target_User__c);
- }
- Map<Id,decimal> AMTarget=new Map<Id,decimal>();
- aggregateResult[] aggRes=[Select Account_Manager__c,SUM(OTC_Unit_Price__c) sumac from OTC_Contract_Product_Line_Items__c where Account_Manager__c = : AMids AND OTC_Status__c= 'Active' Group by Account_Manager__c];
- for(aggregateResult ar:aggRes)
- {
- Id AM=(Id)ar.get('Account_Manager__c');
- double IV=(double)ar.get('sumac');
- AMTarget.put(AM,IV);
- }
- for(Monthly_Target__c tg:trigger.new)
- {
- tg.Portfolio_Total_Revenue__c=AMTarget.get(tg.Monthly_Target_User__c);
- //tg.Active_Amount_Acheived__c=AMTarget.get(tg.Monthly_Target_User__c);
- //tg.Portfolio_Total_Revenue__c=Integer.valueOf(ar.get('sumac');
- }
- }
I have written a test class but the trigger is still showing 0% coverage.
I am unable to post the class here as it is too long.
Can anyone please help me with the test class?
Thanks
Let us know if this will help
All Answers
I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing
Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm
Pleasse check below post sample test class
1) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html
You write a test class for this the same way that you would any other:
- Set up some data for the Trigger to access (in this case it looks like Monthly_Target__c and OTC_Contract_Product_Line_Items__c )
- Instantiate the Trigger - insert or update Monthly_Target__c record.
- Execute a method/methods
- Verify the behaviour with asserts.
Please follow below salesforce Best Practice for Test Classes :-
1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .
Please let us know if this post will help you
private class Test_UpdateTargets {
static testMethod void myUnitTest()
{
// TO DO: implement unit test
Profile p = [select id from profile where name='Dubizzle Standard User'];
User u = new User(
IsActive=True,
Alias= 'Dubiz',
email='emiratesTest@testorg.com',
emailencodingkey='UTF-8',
lastname='Testing',
languagelocalekey='en_US',
localesidkey='en_US',
profileid = p.Id,
timezonesidkey='America/Los_Angeles',
username='emiratesTes1@testorg.com',
CommunityNickname= 'Dub');
insert u;
ID AccRecordTypeID = Schema.SObjectType.Account.getRecordTypeInfosByName().get('OTC-Person Accounts').getRecordTypeId();
ID BusinessAccRecordTypeID = Schema.SObjectType.Account.getRecordTypeInfosByName().get('OTC- Business Account').getRecordTypeId();
ID Contract_RecordTypeID = Schema.SObjectType.Contract.getRecordTypeInfosByName().get('Standard Listings').getRecordTypeId();
Account ObjAccount = new Account(LastName='Test Account',RecordTypeID=AccRecordTypeID,OTC_Blacklisted_Customer__c=false,PersonMobilePhone='234567',Phone='456',PersonEmail='test@gmail.com',Passport__pc=true,OTC_Emirates_ID_Upload__pc=true);
insert ObjAccount;
Account ObjBAccount = new Account(Name='Business Account',RecordTypeID=BusinessAccRecordTypeID,OTC_Blacklisted_Customer__c=false,Phone='456');
insert ObjBAccount;
ObjAccount.PersonMobilePhone= '3333';
ObjAccount.PersonEmail = 'abc@gmail.com';
ObjAccount.Phone = '222';
update ObjAccount;
Contact ObjContact = new Contact(LastName='hjk',FirstName='dfg',email='xyz@gmail.com',AccountID=ObjBAccount.id,OTC_Key_Contact__c=true,MobilePhone='23456');
insert ObjContact;
ObjContact.MObilePhone ='1111';
ObjContact.phone = '345';
ObjContact.Email = 'ssg@gmail.com';
ObjContact.FirstName='hh';
ObjContact.LastName='bbb';
update ObjContact;
Product2 ObjProduct = new Product2(Name = 'Laptop', Family = 'Adaptation');
insert ObjProduct;
Id pricebookId = Test.getStandardPricebookId();
PricebookEntry standardPrice = new PricebookEntry(
Pricebook2Id = pricebookId, Product2Id = ObjProduct.Id,
UnitPrice = 10000, IsActive = true);
insert standardPrice;
//[Select id, Monthly_Target_User__c from Monthly_Target__c Where id = :montTID];
Contract ObjContract = new Contract();
try{
ObjContract = new Contract(AccountID=ObjAccount.ID, Account_Manager__c=u.id,RecordTypeID=Contract_RecordTypeID,StartDate=system.today(),ContractTerm=12,OTC_Price_Book__c=pricebookId);
system.debug('Account===>'+ObjContract.AccountID);
system.debug('OTC_Price_Book__c===>'+ObjContract.OTC_Price_Book__c);
system.debug('Contract==>'+ObjContract);
insert ObjContract;
}catch(Exception e){system.debug('Exception Occured-->'+e.getMessage());}
ObjAccount.PersonMobilePhone= '3333';
update ObjAccount;
ObjContact.phone = '222';
ObjContact.MobilePhone ='34565';
ObjContact.Email = 'dfghg@gmail.com';
update ObjContact;
List<Contract_Products_OTC__c> ContractPrdList = new List<Contract_Products_OTC__c>();
Contract_Products_OTC__c ObjContractPrd1 = new Contract_Products_OTC__c(Associated_Contract__c=ObjContract.id,OTC_Start_Date__c=system.today(),OTC_End_Date__c=system.today().addDays(90),OTC_Product_Name__c=ObjProduct.id);
ContractPrdList.add(ObjContractPrd1);
Contract_Products_OTC__c ObjContractPrd2 = new Contract_Products_OTC__c(OTC_Status__c='Upgrade-Pending Approval',OTC_Discount__c=5,Associated_Contract__c=ObjContract.id,OTC_Start_Date__c=system.today(),OTC_End_Date__c=system.today().addDays(90),OTC_Product_Name__c=ObjProduct.id);
ContractPrdList.add(ObjContractPrd2);
insert ContractPrdList;
ObjContractPrd2.OTC_Referenced_Contract_Products__c=ObjContractPrd1.id;
ObjContractPrd2.OTC_Status__c = 'Upgrade';
ObjContractPrd2.OTC_Discount__c = 2;
update ObjContractPrd2;
OTC_Contract_Product_Line_Items__c ObjLine1 = new OTC_Contract_Product_Line_Items__c(OTC_Contract_Product__c=ObjContractPrd2.id,OTC_Contract__c=ObjContract.id, Account_Manager__c=u.id,OTC_Unit_Price__c = 1000, OTC_Status__c = 'Active');
insert ObjLine1;
OTC_Contract_Product_Line_Items__c ObjLine2 = new OTC_Contract_Product_Line_Items__c(OTC_Contract_Product__c=ObjContractPrd2.id,OTC_Contract__c=ObjContract.id, Account_Manager__c=u.id,OTC_Unit_Price__c = 1000, OTC_Status__c = 'Active');
insert ObjLine2;
//ObjLine1.Cheque_Status__c='Bounced';
//update ObjLine1;
OTC_Cheque_Information__c ObjCheque = new OTC_Cheque_Information__c(Name='1001',OTC_Associated_Contract__c=ObjContract.id,OTC_Cheque_Type__c='Refund');
ObjCheque.OTC_Cheque_Status__c='Pending';
ObjCheque.OTC_Cheque_Received_Date__c=Date.newInstance(2017, 3, 1);
ObjCheque.OTC_Cheque_Cleared_Date__c=Date.newInstance(2017, 3, 5);
ObjCheque.OTC_Cheque_Amount__c=4000000.00;
ObjCheque.Bank_Issuer__c = 'N/A';
insert ObjCheque;
OTC_Cheque_Information__c ObjCheque1 = new OTC_Cheque_Information__c(Name='1002',OTC_Associated_Contract__c=ObjContract.id,OTC_Cheque_Type__c='Security');
ObjCheque1.OTC_Cheque_Status__c='Pending';
ObjCheque1.OTC_Cheque_Received_Date__c=Date.newInstance(2017, 3, 1);
ObjCheque1.OTC_Cheque_Cleared_Date__c=Date.newInstance(2017, 3, 5);
ObjCheque1.OTC_Cheque_Amount__c=4000000.00;
ObjCheque1.Bank_Issuer__c = 'N/A';
insert ObjCheque1;
List<OTC_Allocations__c> AllocList = new List<OTC_Allocations__c>();
OTC_Allocations__c ObjAll = new OTC_Allocations__c(OTC_Allocated_Cheque__c=ObjCheque.id,OTC_Allocated_Contract__c=ObjLine1.id,OTC_Associated_Contract__c=ObjContract.id,OTC_Cheque_Amount__c=200000000);
AllocList.add(ObjAll);
// insert AllocList;
OTC_Allocations__c ObjAll2 = new OTC_Allocations__c(OTC_Allocated_Cheque__c=ObjCheque1.id,OTC_Allocated_Contract__c=ObjLine1.id,OTC_Associated_Contract__c=ObjContract.id,OTC_Cheque_Amount__c=200000000);
AllocList.add(ObjAll2);
ObjCheque.OTC_Cheque_Type__c = 'Cash';
Update ObjCheque;
ObjCheque1.OTC_Cheque_Type__c = 'Security';
Update ObjCheque1;
Monthly_Target__c tg = new Monthly_Target__c( Monthly_Target_User__c = ObjLine1.Account_Manager__c, Start_Date__c = system.today() );
system.debug('Monthly Target ==='+tg);
Map<Id,decimal> AMTarget=new Map<Id,decimal>();
aggregateResult[] aggRes=[Select Account_Manager__c,SUM(OTC_Unit_Price__c) sumac from OTC_Contract_Product_Line_Items__c where Account_Manager__c = : tg.Monthly_Target_User__c AND OTC_Status__c= 'Active' Group by Account_Manager__c];
for(aggregateResult ar:aggRes)
{
Id AM=(Id)ar.get('Account_Manager__c');
double IV=(double)ar.get('sumac');
AMTarget.put(AM,IV);
tg.Portfolio_Total_Revenue__c=AMTarget.get(tg.Monthly_Target_User__c);
ApexPages.StandardController sc = new ApexPages.StandardController(tg);
ctrl_monthlyTargetContracts ctrl = new ctrl_monthlyTargetContracts(sc);
ctrl.getActiveContracts();
ctrl.getpendingContracts();
}
}
}
Monthly_Target__c tg = new Monthly_Target__c( Monthly_Target_User__c = ObjLine1.Account_Manager__c, Start_Date__c = system.today() );
insert tg; // I forgot to insert the monthly target record.
Thanks Amit
Let us know if this will help