Apex unit tests ensure good quality for your Apex code and let you meet requirements for deploying Apex.
Some of the benefits of Apex unit tests are:
- To ensure that your Apex classes and triggers work as expected
- Having a suite of regression tests that can be rerun every time classes and triggers are updated to ensure that future updates you make to your app don’t break existing functionality
- Meeting the code coverage requirements for deploying Apex to production or distributing Apex to customers via packages
- High-quality apps delivered to the production org, which makes production users more productive
- High-quality apps delivered to package subscribers, which increase your customers trust
Example:
Class:
public class TemperatureConverter {
// Takes a Fahrenheit temperature and returns the Celsius equivalent.
public static Decimal FahrenheitToCelsius(Decimal fh) {
Decimal cs = (fh - 32) * 5/9;
return cs.setScale(2);
}
}
Test Class:
@isTest
private class TemperatureConverterTest {
@isTest static void testWarmTemp() {
Decimal celsius = TemperatureConverter.FahrenheitToCelsius(70);
System.assertEquals(21.11,celsius);
}
@isTest static void testFreezingPoint() {
Decimal celsius = TemperatureConverter.FahrenheitToCelsius(32);
System.assertEquals(0,celsius);
}
@isTest static void testBoilingPoint() {
Decimal celsius = TemperatureConverter.FahrenheitToCelsius(212);
System.assertEquals(100,celsius,'Boiling point temperature is not expected.');
}
@isTest static void testNegativeTemp() {
Decimal celsius = TemperatureConverter.FahrenheitToCelsius(-10);
System.assertEquals(-23.33,celsius);
}
}
To view what's running now:
Setup | start typing Apex Test Execution in the Quick Find box | select Apex Test Execution
Steps to Execute Apex Tests:
Setup | start typing Apex Test Execution in the Quick Find box | select Apex Test Execution | Click Select Tests | Select the tests to run. (The list of tests includes only classes that contain test methods)(| To opt out of collecting code coverage information during test runs, select Skip Code Coverage) | Click Run.
You may open the Apex Class to check the coverage or from developer console.
Steps to run from Developer Console:
In developer console, Test | New Run | Select the Test Class | Run
Double click on the class name (as in attached visual) to see the coverage which is 100% here.
Visual: https://www.youtube.com/watch?v=A5ASrL_PZ_o
Reference:
https://help.salesforce.com/s/articleView?id=sf.code_test_execution.htm&type=5
https://trailhead.salesforce.com/content/learn/modules/apex_testing
Comments
Post a Comment