function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
vasu takasivasu takasi 

How to write test class for both 'If 'and 'Else' statements

hi

i have class like

 

public class abc

{

integer a,b,c;

    public void maths()

{

     string s='add';

 

  if(s=='add')

{

   c=a+b;
}

else if(s=='sub')

{
   c=a-b;
}
}

}

 

 

here i want to cover both if and Else blocks.

Please guide me.

Best Answer chosen by Admin (Salesforce Developers) 
JitendraJitendra

Hi,

Please find below code:

 

public class abc
{
	public integer a,b,c;
	public string s;
	public void maths()
	{ 
		if(s=='add')
		{
		   c=a+b;
		}
		else if(s=='sub')
		{
		   c=a-b;
		}
	}
}

@isTest
public class Testabc
{
	static testMethod void testAddMethod()
	{
		abc obj = new abc();
		obj.a = 5;
		obj.b = 5;
		obj.s = 'add';
		obj.maths();
		
		System.AssertEquals(obj.c,10);
	}
	static testMethod void testSubMethod()
	{
		abc obj = new abc();
		obj.a = 5;
		obj.b = 5;
		obj.s = 'sub';
		obj.maths();
		
		System.AssertEquals(obj.c,0);
	}
}

 

 

All Answers

asish1989asish1989

Hi 

  You have to make ist condition true for If block then make condition false for else block.

   Try this

      

private static void testmethod() {
string p = 'add'
string p ='sub'
}

 

 

Did this post answers your questions...if so please mark it solved..so that others get benifited,

 

 

Thanks

asish

JitendraJitendra

Hi,

Please find below code:

 

public class abc
{
	public integer a,b,c;
	public string s;
	public void maths()
	{ 
		if(s=='add')
		{
		   c=a+b;
		}
		else if(s=='sub')
		{
		   c=a-b;
		}
	}
}

@isTest
public class Testabc
{
	static testMethod void testAddMethod()
	{
		abc obj = new abc();
		obj.a = 5;
		obj.b = 5;
		obj.s = 'add';
		obj.maths();
		
		System.AssertEquals(obj.c,10);
	}
	static testMethod void testSubMethod()
	{
		abc obj = new abc();
		obj.a = 5;
		obj.b = 5;
		obj.s = 'sub';
		obj.maths();
		
		System.AssertEquals(obj.c,0);
	}
}

 

 

This was selected as the best answer
Arun Kumar 76Arun Kumar 76
Hi Vasu,

I know its too late to rply here of your question.
You can do in efficient way as well.

@isTest public class Testabc
{
    static testMethod void testMethod()
     {
     list<string> methodtype = new list<string>();
     methodtype.add('add');
     methodtype.add('sub');
  for(string type : methodtype){
           abc obj = new abc();
           obj.a = 5;
           obj.b = 5;
           obj.s = type;
           obj.maths();
           System.AssertEquals(obj.c,10);

   }

       
}