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
Mel LisauMel Lisau 

How can i test the else part of an if else statement ?

I have a class with the following layout 
if (testflag)
{
    //code 1
}
else
{
       //code 2
}
When i create a test for my trigger , I set the testflag to true hence it will fall in the code 1 section .
But my overall test dont give full 100% because the else condition is not met ?
Do i need to create another test that meets the else condition , because i dont want to create 2 test for my trigger  ?
thanks
 
Best Answer chosen by Mel Lisau
Andrew GAndrew G
Yes,  two test is better. more tests is better.

how else can you be truly assured that the code works as expected.  Remember that test code is there to see how your code would work once it is deployed, so testing of each branch from a start state is best practice.  I wonder why the aversion to creating a second test?  Once we have one test, a second is easy.

An basic example of some code to cover
public class sortLightStatus{
  if (light status is ON )
  {
    // some code to turn the light off
  }
  else
  {
       // some code to turn the light on
  }
}
a basic test class:
@istest
private class lightHandlerTest{
  @istest
  static void testLightOn(){
    //insert a light record with status ON
    //do some asserts to check light OFF
  }

  @istest
  static void testLightOff(){
    //insert a light record with status OFF
    //do some asserts to check light ON 
  }
}
and if we wanted to be a good developer maybe a test method with a light with status of NULL and then see how well our initial code is written to handle unexpected exceptions.


Regards

Andrew