To display even and odd numbers using Apex code and its test class in Salesforce, you can use the following example:
// A class that contains a method to display even and odd numbers
// A method that takes a list of integers as input and prints whether each number is even or odd
public static void displayEvenOdd(List<Integer> numbers) {
// Loop through the list of numbers
for (Integer num : numbers) {
// Check if the number is divisible by 2
if (num % 2 == 0) {
// Print that the number is even
System.debug(num + ' is even');
} else {
// Print that the number is odd
System.debug(num + ' is odd');
}
}
}
}
// A test class that contains test methods to verify the functionality of the EvenOdd class
public class EvenOddTest {
// A test method that passes a list of positive integers to the displayEvenOdd method and asserts the expected output
@isTest static void testPositiveNumbers() {
// Create a list of positive integers
List<Integer> numbers = new List<Integer>{2, 3, 4, 5, 6, 7};
// Call the displayEvenOdd method with the list of numbers as input
Test.startTest();
EvenOdd.displayEvenOdd(numbers);
Test.stopTest();
// Get the debug log for the test execution
List<ApexLog> logs = [SELECT LogUserId, Operation, Request, Status, LogLength FROM ApexLog];
// Assert that the log contains the expected output for each number in the list
System.assert(logs[0].Operation.contains('2 is even'));
System.assert(logs[0].Operation.contains('3 is odd'));
System.assert(logs[0].Operation.contains('4 is even'));
System.assert(logs[0].Operation.contains('5 is odd'));
System.assert(logs[0].Operation.contains('6 is even'));
System.assert(logs[0].Operation.contains('7 is odd'));
}
// A test method that passes a list of negative integers to the displayEvenOdd method and asserts the expected output
// Create a list of negative integers
List<Integer> numbers = new List<Integer>{-2, -3, -4, -5, -6, -7};
// Call the displayEvenOdd method with the list of numbers as input
Test.startTest();
EvenOdd.displayEvenOdd(numbers);
Test.stopTest();
// Get the debug log for the test execution
List<ApexLog> logs = [SELECT LogUserId, Operation, Request, Status, LogLength FROM ApexLog];
// Assert that the log contains the expected output for each number in the list
System.assert(logs[0].Operation.contains('-2 is even'));
System.assert(logs[0].Operation.contains('-3 is odd'));
System.assert(logs[0].Operation.contains('-4 is even'));
System.assert(logs[0].Operation.contains('-5 is odd'));
System.assert(logs[0].Operation.contains('-6 is even'));
System.assert(logs[0].Operation.contains('-7 is odd'));
}
}
This example demonstrates how to write a simple Apex class and its corresponding test class. The Apex class has a static method that takes a list of integers as input and prints whether each number is even or odd. The test class has two test methods that pass different lists of integers to the displayEvenOdd method and assert the expected output using debug logs.
Comments
Post a Comment