function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ramssf70Ramssf70 

give me some tips for writing a test class easily

Hi Folks,

Give me some tips for writing test class easily and give me some basic exmaples.

Regards
Ramakrishna
DeepthiDeepthi (Salesforce Developers) 
Hi Ramakrishna,
A test class simply refers to the input required to confirm if instructions and methods used in developing an application or program are working correctly in delivering the desired output. 
Important considerations:
  1. Use the @isTest annotation.
    The test class starts its execution from the "testMethod". 
  2. Cover as many lines as possible. 
  3. At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.
  4. Use System.assert methods to prove that code behaves properly.
  • 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.
    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.
Please follow the link for examples and more information on Test classes:
https://developer.salesforce.com/forums/?id=906F0000000BSo5IAG
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm   (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm  )
http://www.sfdc99.com/2013/05/14/how-to-write-a-test-class/  (http://www.sfdc99.com/2013/05/14/how-to-write-a-test-class/ )

Hope this helps you! Mark this post as Best Answer if it addresses your requirement.
Thanks,
Deepthi
Akshay_DhimanAkshay_Dhiman
Hi  Ramssf70,

I hope this code will help you lot to understand and write test class.

About Test Class:

The Apex testing framework enables you to write and execute tests for your Apex classes and triggers on the Force.com platform. Apex unit tests ensure high quality for your Apex code and let you meet requirements for deploying Apex.

Apex Code:
public with sharing class ContactOneCheck
 {
  public static void checkContact()
  {
  		list<account> aclist= new list<account>();
  		Integer n=0;
	aclist=[select Id, Name, NumberOfEmployees from account limit 10]; // --->Query to get 10 Records of Account from Org
  		list<contact> conlist= new list<contact>();
  		for(account ac:aclist)
{
  		contact con=new contact();
  		con.LastName='Ajay '+n;
  		n++;
  		con.AccountId=ac.Id; //--> Creating LookUp of Account in Contact 
  		conlist.add(con); 
  		}
  	if(conlist.size()>0)
  	insert conlist;
  	System.debug(conlist); // -->Test class does not count 'debug' line
  }   
}

Test Class code for above Apex Code:
@isTest 
public with sharing class ContactOneCheckTestClass
{
    @isTest static void testMethodCaseRecord()
      {
    	Account acc = new Account(); // Creating a  New Account for Test
    	acc.Name = 'Guru Vemuru';
    	acc.NumberOfEmployees = 5;
     	insert acc;
    	system.assert(true,'Account is Inserted');
       	Integer n=0;
   		test.startTest(); //--> Predefined Method for Test Class to Start the Test Execution of Apex Code
    	ContactOneCheck.checkContact(); //--> Calling the Class and their Method for Test.
    	test.stopTest(); //----> Predifined Method to Stop Test Execution 
    }
}

Here the desired output :-
User-added image

Points to remember for Test Classes:-
  • Test class always Start with @isTest.
  • In test class we have to create all the data which getting from query in Apex Code. (For Example : Account Object with its following records Id,Name,NumberOfEmployees).
  • test.startTest() and test.stopTest() must be used in Test Class.

For More Information go through these links Reference:​
  • https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods
  • https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
  • http://www.sfdc99.com/2013/05/14/how-to-write-a-test-class/
  • http://webkul.com/blog/test-classes-in-apex-salesforce/

Regard,
Akshay.
If this answers your query please mark this question as a solved so that it can be filtered out from  unsolved questions.
     
      NILESH RAJ 20NILESH RAJ 20
      Each test class follows a similar pattern:
      Test class in Salesforce starts with @isTest annotation which shows that this particular apex class is a test class.
      Setup of test data. This includes the creation of any data needed by your class. 
      Starting the test by calling Test.startTest() to reset the governor limits.
      Calling your class/method
      Stopping the test by calling Test.stopTest() to reset the governor limits and allow for any async jobs to finish.
      Asserting that your changes have worked
      ​If you have made any change o the record, you need to query for the updates
      Run System.assert, System.assertNotEquals,System.assertEquals to verify that you got the correct data.

      You can check more details test class in salesforce (https://sfdcwisdom.com/test-class-in-salesforce/)
      Suraj Tripathi 47Suraj Tripathi 47
      Hi Ramssf70,

      Test class starts with @isTest annotation.
      Test.startTest() and Test.stopTest() must be used in Test Class.
      Use System. assert methods to check code work properly or not.
      At least 75% of your Apex code must be covered by unit tests.

      for more information go through this link:
      https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_test.htm

      If you find your Solution then mark this as the best answer. 

      Thank you!

      Regards 
      Suraj Tripathi
      Dixie LaneDixie Lane
      We all know that writing tests can be a really tiring and tedious task. It can take hours to write one test, but what if there was an easier https://www.edugeeksclub.com/ way? What if you could automate this process so you don't have to manually do it every time? Well now there is! This blog post will give you some tips on how to write your own test class easily.
      Jason Lee 172Jason Lee 172
      Hi! Thanks for this useful information, as it's very interesting and informative for me! But if you don't have a proper support in writing your tasks, then you must ask it at this fantastic online https://writemyessaytoday.us/ writing company. I highly recommend it from my own cooperation with this agency for the last 2 years of my hard students life!
      David John 55David John 55
      Thanks for sharing this useful information. Students looking for tips from experts writers can take assignment writing services from us. We provide the best and affordable academic assistance to students. For more information, visit @ https://www.globalassignmenthelp.com/uk
      Assignment DeskAssignment Desk
      An application's or program's input is referred to as a "test class," which simply indicates whether or not the methods and instructions used to create the desired output are effective. For writing a test class easily you can find innumerable programming assignment writing service providers throughout the world, Then how should you choose the best and most affordable writers for your assignment? The solution for this problem is that you should check the sample paper first and after that choose the best online assignment help (https://www.assignmentdesk.co.uk/) for your academic task.
      Discounts CodeDiscounts Code
      Certainly! Writing test classes is an essential part of ensuring the reliability and functionality of your code. Here are some tips to help you write test classes more easily and effectively:
      • Understand the Code: Before you start writing a test class, make sure you thoroughly understand the code you're testing. This will help you identify potential edge cases and areas that require specific testing.
      • Follow a Naming Convention: Use clear and consistent naming conventions for your test methods. This makes it easier for you and others to understand what each test is checking.
      • Test One Thing at a Time: Each test method should focus on testing one specific aspect or functionality of your code. This helps isolate issues and makes it easier to identify the cause of a failure.
      • Use Descriptive Test Method Names: A well-named test method should describe what it's testing and what the expected outcome is. This makes it easier to understand the purpose of the test.
      • Arrange, Act, and Assert (AAA): Structure your test methods using the AAA pattern.
      • Arrange: Set up the preconditions for the test.
      • Act: Perform the action you're testing.
      • Assert: Check that the result matches the expected outcome.
      • Use Meaningful Assertions: Choose assertions that clearly express the expected outcome. For example, if you're testing for equality, use assertEquals(expected, actual).
      • Cover Edge Cases: Make sure to test boundary values, edge cases, and any exceptional conditions that might occur.
      • Avoid Hard-Coding Values: Use constants or variables to hold values that are reused across multiple tests. This makes it easier to update them if needed.
      • Mock External Dependencies: When testing code that relies on external services or dependencies, consider using mocks or stubs to isolate the functionality you're testing.
      • Clean Up After Tests: If your tests create any temporary resources or modify state, make sure to clean up after the test is complete. This ensures that subsequent tests aren't affected.
      • Use Test Annotations or Decorators: Depending on the testing framework you're using, leverage annotations or decorators to indicate which methods are tests.
      • Review and Refactor: After writing your initial tests, review them for clarity, completeness, and readability. Refactor if necessary to improve maintainability.
      • Automate Testing: Consider using continuous integration tools or test runners to automate the execution of your tests. This helps catch regressions early.
      • Document Your Tests: Provide comments or documentation to explain the purpose of each test, especially if the logic isn't immediately obvious.
      • Run Tests Frequently: Run your tests often, especially after making changes to the code. This helps catch issues early in the development process.
      By following these tips, you can make the process of writing test classes more efficient and effective, ultimately leading to more robust and reliable code.
      https://www.discountscode.co.uk