Anonim Wd
Anonim Wd

Reputation: 65

PHPUnit Tests constants

I have a class with a constant:

class LoremIpsum {
  const VALUE = '123';

  public function MethodThatUsesConstant()  {
    ...
  }
}

When I want to unit test a method that uses this constant, should I use the constant from the real class or should I create a new constant in the Test Class with the same value as the real constant?

Ex:

class LoremIpsumTest {
    const VALUE = '123';

    public function testMethodThatUsesConstant() {
       ...
    }
}

or

class LoremIpsumTest 
{
     //this test uses the real constant

        public function testMethodThatUsesTheRealConstant() {
           /**$const = \Namespace\LoremIpsum::VALUE **/
        }
    }

Upvotes: 1

Views: 3099

Answers (3)

cn0047
cn0047

Reputation: 17051

I'd rather advice you to follow principle and use only original constant, moreover you'll have single point of true.

Upvotes: 1

rob006
rob006

Reputation: 22144

That depends on what this constant represents. If this is a business requirement (for example "widget should display 20 rows per page" and const ROWS_PER_PAGE = 20) you should NOT reuse this constant in test. Changing code should not change business requirements (which should be represented by tests). Creating such dependency may make the whole test completely pointless - I can change ROWS_PER_PAGE to 10 and test will pass, event if requirements are clear that there should be 20 rows per page.

And yes, it does not look DRY, but this is the whole point of tests - you're creating two different representations of the same requirement: code that renders 20 rows per page and test that checks that there is a 20 rows per page. Tests duplicate code by design, you should not worry too much about duplicated constants.

Upvotes: 2

Schleis
Schleis

Reputation: 43690

I would use the actual constant for my tests but it depends on what you are using the constant for. Your examples don't provide enough context for your specific use case.

If you are using the value of the constant as an ID that gets returned, I would use the real constant in my tests. When I am checking the value of the return, it doesn't matter what the actual value is but that it is this constant. The existence of the constant is part of the public interface of the class and checking that the value ensures that it actually exists. Changing this value doesn't change the behavior of the class so the tests should always pass.

If the constant is used in a calculation, I wouldn't worry about it at all. In this case, the constant becomes an implementation detail. In this case, I would have my tests have actually calculated values for a given set of inputs. Having my test perform the calculation for me may seem to be convenient but there is a risk of duplicating a math error as you will likely copy-paste the algorithm. So in these tests, I wouldn't use any constant at all.

Upvotes: 1

Related Questions