How do I use system assert?

1.7K    Asked by ananyaPawar in Salesforce , Asked on Sep 23, 2022

I am new to Salesforce. I wrote the test class for the program below, but it is simple. I want to make use of system.assert(), system.assertequals() and system.runas() commands methods for the below test method, to better understand their use. Please help me with this by providing examples of where I should implement them into my test test class as I complete it.

APEX CLASS

public class testinterview {
    public String getOutput() {
        return null;
    }
public string fname{set;get;}
public patient__c pt{set;get;}
public list pat{set;get;}
public testinterview()
{
}
public void input()
{
pt=new Patient__c();
pt.FirstName__c=fname;
insert pt;
}
public void output()
{
pat= new list();
 pat=[select Firstname__c from Patient__c ];
}
}
TEST CLASS I HAVE WRITTEN
@isTest
private class mytest{
static testMethod void testinterviewTest() {


testinterview inter=new testinterview();

inter.input();

inter.output();

   }

}


Answered by Alison Kelly

From System Class Apex documentation:


System.assert(): system Assert that the specified condition is true. If it is not, a fatal error is returned that causes code execution to halt.

System.assertEquals(): Asserts that the first two arguments are the same. If they are not, a fatal error is returned that causes code execution to halt

System.runAs(): Changes the current user to the specified user. (execute the test as a given user)

Please see the Testing Example of the Apex Code Developer Guide

As a simplistic example consider the following class:

public class GreetingClass {
     public String sayHello(String first_name){
           return "Hello "+first_name;
     }
}
And the following is a test method for that class:
@isTest
private class testGreetings {
    static testMethod void testSayHello(){
            GreetingClass greeting = new GreetingClass();
            // you can add a System.runAs() here wrapping this call to get outcomes for a given user
            // test that sending 'Joe' as parameter to the sayHello method, the output is 'Hello Joe'
            System.assertEquals(greeting.sayHello('Joe'),'Hello Joe')
    }
}

Your Answer

Answer (1)

Using assert in programming, particularly in Python, is a way to enforce that certain conditions hold true during the execution of your code. It helps in debugging by catching errors early and providing meaningful error messages.


Basic Syntax

The basic syntax for using assert in Python is:

  assert condition, "error message"

How It Works

  • Condition: This is the expression that you expect to be True. If the condition is False, the program will raise an AssertionError.
  • Error Message: (Optional) This is the message that will be displayed if the assertion fails.

Example

Here are a few examples to illustrate the usage:

Simple Assertion

x = 5
assert x > 0, "x should be positive"

This will not raise an error because x is indeed greater than 0.

Failed Assertion

y = -3
assert y > 0, "y should be positive"

This will raise an AssertionError with the message "y should be positive".

Using Assertions in Functions

Assertions can be used to check conditions in functions, especially to validate inputs and outputs.

def divide(a, b):
    assert b != 0, "The divisor b cannot be zero"
    return a / b


result = divide(10, 2) # This works fine
result = divide(10, 0) # This raises an AssertionError: The divisor b cannot be zero

Assertions for Debugging

Assertions are primarily used for debugging purposes. They can be turned off globally by running Python with the -O (optimize) switch, which means they shouldn't be used for regular runtime checks but rather for catching programming errors during development.

Practical Usage Tips

1. Input Validation: Use assertions to check if the inputs to your functions are as expected.

def calculate_area(radius):
    assert radius >= 0, "Radius cannot be negative"
    return 3.14 * radius * radius

2. Output Verification: Use assertions to verify the outputs from your functions.

def square(x):
    result = x * x
    assert result >= 0, "The result should be non-negative"
    return result

Invariant Conditions: Use assertions to enforce invariants within your code.

def process_data(data):
    assert isinstance(data, list), "Data should be a list"
    # Process data
    assert len(data) > 0, "Data should not be empty after processing"

Conclusion

Assertions are a powerful tool to catch bugs early by making your assumptions explicit. They should be used during the development and debugging phases to ensure that your code behaves as expected. However, remember not to use them for handling runtime errors in a production environment, as they can be disabled and are not a substitute for proper error handling.

Example in a Script

Here’s a simple script using assertions:def factorial(n):
    assert n >= 0, "n must be a non-negative integer"
    if n == 0 or n == 1:
        return 1
    result = 1
    for i in range(2, n + 1):
        result *= i
    assert result > 0, "result should be positive"
    return result
print(factorial(5)) # This works fine
print(factorial(-1)) # This raises an AssertionError: n must be a non-negative integer

Using assertions effectively can help you catch and diagnose errors early, making your code more robust and easier to maintain.


5 Months

Interviews

Parent Categories