Showing posts with label Test Claas. Show all posts
Showing posts with label Test Claas. Show all posts

Friday, July 8, 2016

System.StringException: Invalid id Error in Salesforce

Usually this kind of error we will be receiving in test classes.This is due to when your working with any kind of relationship fields in objects.Let me explain with an example below

Error:

We have a two objects called Order__c and Time__c and these two objects are having a lookup relationship where Order__c is Child and Time__c is a parent.Now i have to create a test record for Time__c along with Order__c and then I want to update Time__c record Order__c with null value.
@isTest 
private class TestTimeEntry {
    static testMethod void validateTime() {
        Order__c ord = new Order__c();
        ord.Name ='Test Order';
        insert ord;
        
        Time__c tm1 = new Time__c();
        tm1.Order__c = ord.id;
        tm1.name = 'test time';
        insert tm1;
        
        Time__c tm2 =[Select id,name,Order__c from Time__c where id=:tm1.id];
        tm2.Order__c =''; //At runtime we will receive Error here
        update tm2;
    }
}

Root Cause:

So when you run this test class you will receive a runtime error called System.StringException: Invalid id  at an update statement due to assigning an empty string(empty space) to Order__c.Usually all relationship fields will accepts Ids or null key word. 

Work Around Solution
So when your trying to assign an empty value for relationship field we have to specify null keyword instead of an empty space('')
@isTest 
private class TestTimeEntry {
    static testMethod void validateTime() {
        Order__c ord = new Order__c();
        ord.Name ='Test Order';
        insert ord;
        
        Time__c tm1 = new Time__c();
        tm1.Order__c = ord.id;
        tm1.name = 'test time';
        insert tm1;
        
        Time__c tm2 =[Select id,name,Order__c from Time__c where id=:tm1.id];
        tm2.Order__c =null; //An empty space replaced with null keyword
        update tm2;
    }
}



Thanks for visiting...Enjoy!


Wednesday, June 22, 2016

25 Basic Deployment or Test Classes Issues During Deployment in Salesforce

1.System.DmlException: ConvertLead failed. First exception on row 0; first error: ENTITY_IS_DELETED, entity is deleted: []

2.System.NullPointerException: Argument 1 cannot be null

3.System.LimitException: Too many SOQL queries: 101

4.System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, SampleTrigger: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id a4980000001paQSAAY; first error:

5.first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, SampleTrigger: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.SampleTrigger: line 181, column 1: [] Trigger.ChildTrigger: line 85, column 1 Trigger.ChildTrigger: line 50, column 1: []

6.System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OrderRequest: execution of AfterInsert caused by: System.DmlException: Process failed. First exception on row 0; first error: NO_APPLICABLE_PROCESS, No applicable approval process was found.: [] Trigger.OrderRequest: line 81, column 1: []

7.System.LimitException: Too many query rows: 50001

8.No such column 'Unique_Key__c' on entity 'End_Date_Ruleset__c'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.

9.This custom field is referenced elsewhere in salesforce.com. : Field Updates.

10.Field Project_Quarter__c does not exist. Check spelling.

11.In field: field - no CustomField named Job_Profile__c.ID_to_get_cluster_value__c found

12.An object 'Lead-ETS/WMI Lead Page Layout' of type Layout was named in package.xml, but was not found in zipped directory

13.An object 'Lead.IsUKCreatedLead__c' of type CustomField was named in package.xml, but was not found in zipped directory

14.System.DmlException: ConvertLead failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, System.DmlException: Update failed. First exception on row 0 with id 00Q8000001e17G8EAI; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateAcctShippingAddr: execution of AfterUpdate caused by: System.LimitException: Too many SOQL queries: 101

15.Fatal Error null: The changes you requested require salesforce.com to temporarily lock your organization's administration setup. However, the administration setup has already been locked by another change. Please wait for the previous action to finish, then try again later.

16.Invalid field Billing_Email__c for SObject Account

17.System.QueryException: List has no rows for assignment to SObject

18.Stack Trace: Class.SendEmailQuote.generateEmailBody: line 941, column 1 Class.SendEmailQuote.<init>: line 151, column 1 Class.TestSendEmailQuote.Test1: line 73, column

19.Cannot update a field to a Lookup, MasterDetail, or Hierarchy from something else

20.Apex class 'QuoPDF_US' does not exist

21.Dependent class is invalid and needs recompilation: QuoPDF_US: line 58, column 20: Invalid type: Sales_Cond_Type__c

22.Invalid type: Sales_Type__c

23. new_quote does not exist or is not a valid override for action New.

24. Field is not writeable: Service_Order__c.CreatedById

25. Code Coverage Failure Your code coverage is 74%. You need at least 75% coverage to complete this deployment.


Thanks for visiting...Enjoy!

Method only allowed during testing" Error in Test Classes

Issue:

Lets take an example where you have a test class which contains Test.startTest() and Test.stopTest() methods and you have more than one test method in test class.When you run this test class in any way it touches any class that implements the Queueable interface your test classes methods more than one will fails

WorkAround:

Split all your test class methods into individual test class in salesforce. For more information please refer salesforce known issues page 


Thanks for visiting...Enjoy!

Tuesday, April 19, 2016

First error: NO_APPLICABLE_PROCESS, No applicable approval process was found

When your trying to make any kind of deployment on Production by default all the test classes will be run .To make smother deployment we need to have at least 75% code coverage .Recently when I'm making deployment to production I end up with the below error.

Deployment /Test Class Error:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ORequestTrigger: execution of AfterInsert caused by: System.DmlException: Process failed. First exception on row 0; first error: NO_APPLICABLE_PROCESS, No applicable approval process was found.: [] Trigger.ORequestTrigger: line 81, column 1: []

Reason for the Issue:

If you running any Test class that in turn causes a Main class or Trigger to submit the Test record for an Approval Process (through Apex coding) and If that particular record is failing to meet at least one of the Approval Processes Entry Criteria then it will fail with above error.

Work Around Solution:

Modify the test record data as per the entry criteria of any one of required Approval Process.


Thanks for visiting...Enjoy


Thursday, January 21, 2016

How to get code coverage report class by class in Salesforce

Some times we will come across situation where we need to increase code coverage of 1% or 2% to get the 75% .To improve code coverage first we need to know the coverage report class by class but unfortunately in salesforce we don't have any option to get the report in single shot.To do this we have to navigate through the each and every class and we have to note down the coverage which is very headache thing and as well as time consuming process.

No worries,for every problem their would be a solution but only thing is that we need to explore for that one.To get the code coverage report class by class we can use ASIDE.IO. I would say Great thanks for the ASIDE.IO team because this is the number one tool to get the code coverage report class by class in salesforce with simple click only.Now I will explain how to use feature .

1. Login to ASIDE.IO as shown as below image by selecting type of the login



2.Once your login it will show your name Please verify whether you logged into correct instance or not and Click on < symbol to get more options


3.On click on < Symbol you will be getting more option as shown in below image.


4.Click on Test button to get more Unit Testing related options on left side as shown in below image


5.Click on Coverage Report button to get Click Here to Generate the Report option on Right Side


6. Click on the Generate the report button to download the coverage report in the form of .csv

    

7. Sample downloaded report looks likes as below image
  



8.Downloaded report contains below components we need to more concentrate on last 2 colums


  • Class Name,Coverage (%)
  • Total Lines
  • Lines Uncovered
  • Lines Covered
  • Remaining Coverage (%)
  • % Of Organization Total
  • Organization Potential Gain (%)

Hope this helps for everyone...Enjoy!!!

For more update please join this site or just like my Facebook page I Love Coding..You?


Tuesday, January 19, 2016

Best Practices for writing Test Class in Salesforce

  • You must have at least 75% of your Apex covered by unit tests to deploy your code to production environments. In addition, all triggers must have some (at least 1%) test coverage.
  • We recommend that you have 100% of your code covered by unit tests, where possible.
  • Calls to System. Debug are not counted as part of Apex code coverage in unit tests.
  • Use Test.loadData () method to load test data from Static resources.
  • Use Test.starttest() and Test.starttest() to reset governor limits.
  • Use test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in any test method in the test class.
  • In the case of conditional logic (including ternary operators), execute each branch of code logic.
  • Make calls to methods using both valid and invalid inputs.
  • Complete successfully without throwing any exceptions, unless those errors are expected and caught in a try…catch block.
  • Use Limits Class to avoid governor limits related issues.
  • Always handle all exceptions that are caught, instead of merely catching the exceptions.
  • Use System.assert methods to prove that code behaves properly.
  • Use the runAs method to test your application in different user contexts.
  • Use the isTest annotation. Classes defined with the isTest annotation do not count against your organization limit of 2 MB for all Apex code. See IsTest Annotation.
  • Exercise bulk trigger functionality—use at least 20 records in your tests.
  • Use the ORDER BY keywords to ensure that the records are returned in the expected order.
  • Not assume that record IDs are in sequential order.
  • Record IDs are not created in ascending order unless you insert multiple records with the same request. For example, if you create an account A, and receive the ID 001D000000IEEmT, then create account B, the ID of account B may or may not be sequentially higher.
  • On the list of Apex classes, there is a Code Coverage column. If you click the coverage percent number, a page displays, highlighting all the lines of code for that class or trigger that are covered by tests in blue, as well as highlighting all the lines of code that are not covered by tests in red. It also lists how many times a particular line in the class or trigger was executed by the test
  • Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the expected outcome, and so on.
  • Test the classes in your application individually. Never test your entire application in a single test.
  • Set up test data:
·         Create the necessary data in test classes, so the tests do not have to rely on data in a particular organization.
·         Create all test data before calling the Test.starttest () method.
·         Since tests don't commit, you won't need to delete any data.
  • If you are running many tests, consider the following:
·         In the Force.com IDE, you may need to increase the Read timeout value for your Apex project. See https://wiki.developerforce.com/index.php/Apex_Toolkit_for_Eclipse for details.
·         In the Salesforce user interface, you may need to test the classes in your organization individually, instead of trying to run all of the tests at the same time using the Run All Tests button.
·         Create Test Suites of Commonly Used Apex Test Classes Available only from Spring 16.

·         Check the disable parallel apex testing when your performing  Run All test

Aside.io for Salesforce

Aside.io is a Salesforce IDE ,up in the cloud ,which is built on top of the different API's like Metadata API and Tooling API .ASIDE is a free and full-featured Salesforce IDE built from the ground up for efficient delivery, design, and testing of Apex and Visualforce code.It's a very good tool to perform the Quick Development of code,Quick deployments,Running Test Classes and Performing the Queries.

Features:

1.CODE EDITOR:

  • Fast Saving the apex code without any dialog.
  • Rich User Interface with Auto complete features and highlighting the invisible characters.
  • Modifying the Static Resources directly in salesforce zip file without downloading.





















  • Run unit tests in three different ways: all at once, by query, or through individual selection.
  • View the Test classes results clearly with help of Stack Trace Parser.
  • Getting the code coverage report for all classes or set of classes.





















3.DEPLOY MANAGER:
  • Retrieving the components without building any package.xml.
  • Drag and Drop feature to Deploy or Retrieve the components from/into the salesforce.
  • Quick generation of the package.xml to share with others.





















4.QUERY TOOL:
  • Fetching the data from Standard Objects,Custom Objects,Custom Settings etc.
  • Export the query result as the form of CSV.
  • Easy way of Sharing the Query Results with others.
  • Quick Creation,Modifying or Deletion of the records.




















In my next post I will share How to use this Aside.io for development and deployments etc.


Keep watching the site for more updates enjoy......!

Thursday, January 7, 2016

How to set Createddate Field value for Test Record in Salesforce Test class

(Note: The feature we are discussing here is as per the Salesforce Spring 16 preview release notes,So this feature is available from Spring 16 release of Salesforce, but features may or may not be available after the Spring 16 go to live )

Before Spring 16 if you are inserting let assume 20 test records in salesforce test class for all those 20 test records the created date is same .If you are working any scenario like to fetch only latest records 20 you will be getting all that 20 records with same created date because all records are inserted with same date so you can't guaranty that in which order they are coming even if you are using order by created date.

From Spring 16 release releasing this great feature to set the created date by the developer for the test records in salesforce test classes (It may or may not be released in Spring as per the note above).

The new Test class method called Test.setCreatedDate(RecordId,DateTime) which allows to set the created date for the test records in salesforce test class.

How to use:
1 . Create a test record in test class.
2.  Pass that record Id along with date time that you want set to Test.setCreatedDate(Id,DateTime).

 @isTest   
 private class SetCreatedDateTest {  
   static testMethod void testSetCreatedDate() {  
     Account a = new Account(name='Test Account');  
     insert a;  
     Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));  
     Test.startTest();  
     Account myAccount = [SELECT Id, Name, CreatedDate FROM Account   
                WHERE Name ='Test Account' limit 1];  
     System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));  
     Test.stopTest();  
   }  
 }  

Key points:
1.All database changes are rolled back at the end of a test. You can’t use this method on records that existed before your test executed.
2.You also can’t use setCreatedDate in methods annotated with @isTest(SeeAllData=true), because those methods have access to all data in your org.
3.This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null.
4. You can see the doc related to this setCreatedDate at Reference Doc for SetCreatedDate.

I think now everyone is eagerly waiting for this new feature.Enjoy....!