8

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.

APEX CLASS
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();
pt.FirstName__c=fname;
insert pt;
}

public void output()
{
pat= new list<patient__c>();
 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();
   }
}

1 Answer 1

9

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:

@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')
    }
}
1
  • 4
    It doesn't matter really but I think the expected value is supposed to come first, like System.assertEquals('Hello Joe',greeting.sayHello('Joe'))
    – codeulike
    Mar 20, 2018 at 14:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .