DEV Community

Cover image for What Hollywood Can Teach You About Writing Good Unit Tests
Joe Eames for Thinkster

Posted on Edited on

What Hollywood Can Teach You About Writing Good Unit Tests

There’s a surprising number of parallels between a good unit test and a good movie. Learning to write good unit tests is important since good unit tests are proven to increase velocity, while bad unit tests can have a detrimental effect on velocity. So let’s break down some of the elements of a good movie, and what that can teach us about good unit tests.

  • A good movie takes time to establish character and motivations — a good unit test has the important parts of the initial setup in the test itself, and not in the beforeEach.
  • A good movie doesn’t spend unnecessary time before the action — a good unit test puts uninteresting setup into the beforeEach.
  • A good movie shows characters undergoing meaningful change — a good unit test covers a meaningful state change.
  • A good movie shows the protagonist triumphing — a good unit test uses asserts appropriately to demonstrate correctness of code.
  • A good movie doesn’t try to develop too many characters (sorry Game of Thrones fans) — a good unit test covers a single state change.
  • A good movie has a clear beginning, middle, and end — a good unit test has the same with the AAA pattern: Arrange, Act, Assert.
  • A good movie has a single climax — a good unit test only tests a single state/state change
  • A good movie doesn’t take too long to end (sorry Return of the King fans) — a good unit test has a single “logical” assert and not a long series of different asserts.
  • A good movie is filmed with the audience in mind — a good unit test is written with readability in mind.
  • A good movie is filmed because someone had a story they needed to tell — a good unit test is written because a piece of code truly needed to be tested, and not just because a developer was jumping through hoops, or trying to hit a coverage requirement.
  • A good movie is easy to follow and doesn’t confuse the audience — a good unit test doesn’t make use of branching or looping logic.

Did I miss any other parallels between good movies and good unit tests?

Happy coding!

Signup for my newsletter at here.
Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster

Top comments (0)