How do I use system.assert, system.assertequals, as in my unit test?

  • I am new to Salesforce. I wrote test class for below program, 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.

    public class testinterview {
        public String getOutput() {
            return null;
    public string fname{set;get;}
    public patient__c pt{set;get;}
    public list<patient__c> pat{set;get;}
    public testinterview()
    public void input()
    pt=new Patient__c();
    insert pt;
    public void output()
    pat= new list<patient__c>();
     pat=[select Firstname__c from Patient__c ];


    private class mytest{
    static testMethod void testinterviewTest() {
    testinterview inter=new testinterview();
  • From System Class Apex documentation:

    System.assert(): Asserts 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:

    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')

    It doesn't matter really but I think the expected value is supposed to come first, like `System.assertEquals('Hello Joe',greeting.sayHello('Joe'))`

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used