Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

How do I use system assert?

Asked by Ananya Pawar Sep 23, 2022 3.6K views 2 answers
Share

About this question

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();

   }

}


Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on May 30, 2024

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.


Was this helpful?

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.