1

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?

1
  • 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 '14 at 17:02
5

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());
    }
}
0

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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