Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

How can I write a test method for the following class?

public Class checkRecursive
{
  private static boolean run = true;
  public boolean runOnce() {
    if (run)
    {
      run = false;
      return true;
    }
    else
    {
      return run;
    }
  }
}

I am trying like this

@isTest

public class recursiveTests {

  public static testMethod void testrecursive() {
    test.starttest();
    checkrecursive cr = new checkrecursive();
    cr.runOnce();
    test.stoptest();
  }
}

But it covers nothing. How can I do this?

share|improve this question
    
Note that checkRecursive will not run as expected during unit tests; the static variable doesn't reset during test execution over multiple trigger contexts in the same test method. –  Mike Chale Jun 21 at 17:02

2 Answers 2

up vote 4 down vote accepted

The first time runOnce() is called it is expected to return true, any further calls will return false. So we just need to write the test to assert that this is the case.

@isTest
public class RecursiveTests {

    @isTest
    static void testRecursive() {
        CheckRecursive cr = new CheckRecursive();

        System.assertEquals(true, cr.runOnce());

        System.assertEquals(false, cr.runOnce());
        System.assertEquals(false, cr.runOnce());
        System.assertEquals(false, cr.runOnce());
    }
}
share|improve this answer

I actually copied your code exactly in my dev org and ran tests and I am getting 83% coverage. Are you sure you are looking at the coverage of the class itself and nit the test class?

enter image description here

share|improve this answer
    
It shown as none –  Salesforce developer Jun 21 at 17:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.