You need to sign in to do that
Don't have an account?
Manid
plz write test class for below code i tried but failed
public class DmlExample{ public account acc{get;set;} public DmlExample(){ acc=new account(); } public pagereference DmlExam(){ integer c=[select count() from account where name=:acc.Name]; if(c>0){ apexpages.Message msg=new apexpages.Message(apexpages.Severity.ERROR,'duplicate is trying to insert'); apexpages.addmessage(msg); return null; } else{ insert acc; pagereference p=new pagereference('/'+acc.id); return p; } } public void cancelling(){ acc=null; } }
Here is a solution 100% test coverage + testSetup + all the assertions for object creations and an error message. A nice exercice for writing a test class.
Regards
All Answers
Hi,
Give it a try creating 2 accounts with same name and this class should be covering easily...!!!
Hope this helps ......!!
Please mark as best answer if the above helps ...!!!
Here is a solution 100% test coverage + testSetup + all the assertions for object creations and an error message. A nice exercice for writing a test class.
Regards
It is also different for extensions with standard (list) controller.
public class DmlExample2 { // constructor : test: DmlExample2 dml = new DmlExample2 ();
public account acc {get;set;}
public opportunity opty {get;set;}
public DmlExample2(){
acc=new account();
opty=new opportunity();
}
public pagereference saving(){
// navigation : test : new ctrl.acc + ctrl.opty before ctrl.saving() + assertions after for the return page and the created objects
insert acc;
opty.accountid=acc.id;
insert opty;
pagereference p=new pagereference('/'+acc.id);
return p;
}
public void cancel(){ // simple method : test : ctrl.cancel();
acc=new account();
opty=new opportunity();
}
}
The missing technique here is for testing the return page reference.
PageReference mypage = ctrl.saving();
system.debug(mypage.getContent());
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/apex_System_PageReference_methods.htm
With this first indications, try to write your test class by yourself and post it here if you need help.
Regards
Alain
I give you the techniques for writing a test class in bold above.
Try and post your own test class (if you might not be able to realize it correctly just post the code of your failed test class here and I will fix it)
Let us know if this will help you
You don't have any assertion with this solution (system.assert) and that could surprise.
You don't know how to test the result of PageReference mypage = ctrl.saving();
For minimal functional unit tests, you can test moreover (not mandatory for Salesforce) if the objects are well created and the navigation is correct (pagereference) using system.assert after each function call (obj.saving(); is the object created?)
That is the theory but in the real world, you will always see these test classes for a good code coverage but the functional tests (system.assert) should be also "mandatory" for minimal functional unit tests. It is difficult to write all the tests (nominal case with all the exceptions).
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
trigger VisitCompletionExpenseItemCreation on Visits__c (after update) {
for( Id visitId : Trigger.newMap.keySet() ){
Visits__c visitEntry = Trigger.newMap.get(visitId);
//if(Trigger.oldMap.get(visitId).Visit_Mark_Complete__c != visitEntry.Visit_Mark_Complete__c && visitEntry.Visit_Mark_Complete__c == 'Yes'){
if(Trigger.oldMap.get(visitId).Status__c != visitEntry.Status__c && visitEntry.Status__c == 'Completed'){
List<Visits__c> visitData = Database.query('select Visit_Owner__c ,Sequence_No__c,Check_in_Address__c , Check_out_Address__c ,Check_out_Location__c,Checkin_Location__c, Retailer_Dealer__c,Retailer_Dealer__r.City__c from Visits__c where Id = :visitId ');
String fromAddress = visitData[0].Check_in_Address__c;
Location fromLocation = visitData[0].Checkin_Location__c;
Id ownerId = Trigger.oldMap.get(visitId).Visit_Owner__c;
String ownerQuery = 'select Id,CheckIn_Address__c,CheckIn_Location__c from Attendance__c where Team__c = :ownerId AND Attendance_Date__c = TODAY';
System.debug(ownerQuery);
if(visitData[0].Sequence_No__c == 1){
List<Attendance__c> visitOwnerData = Database.query(ownerQuery);
for(Attendance__c ownerAttendence : visitOwnerData ){
fromAddress = ownerAttendence.CheckIn_Address__c ;
fromLocation = ownerAttendence.CheckIn_Location__c;
}
}
//Team Data
Id teamId = visitData[0].Visit_Owner__c;
List<String> monthList = new List<String>{'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'};
Date todayDate = Date.today();
String month = monthList[todayDate.month()-1];
String status = 'Draft';
Id expenseId = null;
Team__c teamDetails = new Team__c();
String queryt = 'select Id, Manager__c, City__c from Team__c where Id = :teamId';
List<Team__c> teamList = Database.query(queryt);
if(teamList.size()>0){
for(Team__c team : teamList){
if(team != null)
teamDetails = team;
}
}
if(teamDetails.City__c == visitData[0].Retailer_Dealer__r.City__c){
List<Expense__c> expenseList = Database.query('select Id from Expense__c where Month__c = :month AND Expense_Owner__c = :teamId AND Expense_Status__c = :status' );
if(expenseList.size() > 0){
expenseId = expenseList[0].Id;
}else{
Expense__c exp = new Expense__c();
exp.Month__c = month;
exp.Expense_Status__c = status;
exp.Expense_Owner__c = teamId;
exp.Expense_Approvar__c = teamDetails.Manager__c;
if(teamDetails.City__c == visitData[0].Retailer_Dealer__r.City__c){
exp.Expense_Type__c = 'Local Expense';
}else{
exp.Expense_Type__c = 'None';
}
upsert exp;
expenseId = exp.Id;
}
}
System.debug(expenseId);
if( visitData[0].Check_out_Location__c != null && fromLocation != null ){
Double distance = Location.getDistance(visitData[0].Check_out_Location__c, fromLocation, 'km');
Expense_Item__c expenseItem = new Expense_Item__c ();
expenseItem.Expense__c = expenseId;
expenseItem.Month__c = monthList[todayDate.month()-1];
expenseItem.From__c = fromAddress;
expenseItem.To__c = visitData[0].Check_out_Address__c;
if(distance > 0){
expenseItem.System_calculated_Kilometer__c = distance;
expenseItem.Kilometers_Travelled__c = distance;
}
expenseItem.Team__c = ownerId;
expenseItem.Customer__c = visitData[0].Retailer_Dealer__c;
expenseItem.Visits__c = visitData[0].Id;
expenseItem.Expense_Item_Approver__c = teamDetails.Manager__c;
expenseItem.Approved_by_Manager__c = true;
expenseItem.Date__c = Date.today();
expenseItem.Expense_Status__c = 'Draft';
expenseItem.Kilometers_Travelled__c = 0;
if(teamDetails.City__c == visitData[0].Retailer_Dealer__r.City__c){
expenseItem.Expense_Type__c = 'Local Expense';
}else{
expenseItem.Expense_Type__c = 'None';
}
upsert expenseItem;
System.debug(expenseItem.Id);
}
else
{
System.debug('Checkout Location Missing');
}
}
}
}