tldr: This MR provides an example of clarifying/simplifying tests by removing conditional logic from them.

I've opined before about the importance of banishing conditional logic from unit tests. I like this statement of the best practice:

Unless you want to write unit tests for your unit tests, don’t add calculations or logic to your unit tests. The code needs to be simple, with a cyclomatic complexity of one.

Logic obscures the purpose of the tests, and even with the purpose explained, the complexity of the code may reduce the readers confidence in the test.

The below MR provides an example of doing this by converting conditional logic in \Drupal\Tests\package_manager\Kernel\FileSyncerFactoryTest::testFactory() with a simple values in the data provider. Observe how it 1) makes the test method itself terse, readable, and clear. It would be difficult to misunderstand. 2) The data provider contains both the condition and the expectation, making it a set of complete, declarative statements. The test case is separated into its two logical parts: the expectations, and the behavior under tests. Further benefits might be enumerated, but I leave them to the imagination of the reader. 😉

* "There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies." - Tony Hoare

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

TravisCarden created an issue. See original summary.

traviscarden’s picture

Assigned: traviscarden » Unassigned
Status: Active » Needs review

Oops. 🙄

phenaproxima’s picture

Assigned: Unassigned » traviscarden
Status: Needs review » Reviewed & tested by the community

Yeah, this is much better. If you remove the @throws from the method's doc comment, I'll commit this.

phenaproxima’s picture

Assigned: traviscarden » Unassigned
Status: Reviewed & tested by the community » Fixed

Gratefully merged into 3.0.x. Thanks!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.