How do I use system assert?

1.3K    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

Interviews

Parent Categories