Avoid changing your code purely for a test

Even if it's just to make a property public

Joel Clermont
Joel Clermont
2024-02-13

We have a rule in our projects: never alter application code just to make it easier to test.

Yes, it's possible that writing tests will lead you toward a better design. That's encouraged, and not what we're talking about.

As an example of the type of change we avoid: Don't change a protected property to be public just so you can read it and make a test assertion.

So are we stuck? Do we have to set up a big complicated feature test with a ton of setup, just to get at the logic we want to test?

No, we can keep a nice isolated test. PHP reflection to the rescue! While we don't recommend going overboard with reflection, it can come in handy in this scenario.

In fact, we have two very simple helper methods that we pull into every project's test suite, to make it easy to inspect protected and private properties.

With that approach, we can still make the same test assertions without messing around with application code.

Here to help,

Joel

P.S. If you're clicking around the project standard linked above and like how we work, we might work well together.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.