1 of 18

Slide Notes

DownloadGo Live

Unit Testing Tips

Published on Nov 18, 2015

No Description

PRESENTATION OUTLINE

Unit Testing Tips

September 2nd, 2015

Why write unit tests?

Photo by Stéfan

To find bugs and regressions?

"Testing is not frosting; it is flour or sugar for your cake."
- Misko

Photo by Rachid Lamzah

Why write unit tests?

  • Not great at finding bugs or regressions
  • Most useful for designing robust software

How do unit tests help design?

  • Gives a clear overview and documents the behaviors of your component
  • Encourages developers to write modular and reusable code that executes only one aspect of the desired functionality
  • Makes it easier to refactor and expand your code with the knowledge that existing behaviors are still functioning

Since unit tests are most helpful for the design of our software, we should write unit tests from the very beginning of our projects.

Photo by @boetter

Unit Tests vs. Integration Tests

Unit tests: contain a lot of knowledge about the behavior of a single unit of code. There is no knowledge or assumptions about any other part of the codebase.

Integration tests: contain no knowledge of how the code is structured, but verify how the whole system works for the end users. How code is refactored and restructured doesn't affect the outcome.

Good Tests vs. Bad Tests

Photo by JD Hancock

Bad Unit Tests

  • Don't prove much
  • Break when design or copy changes
  • Break when other areas of the code change
  • Rely on network or database connections
  • Are hard to maintain

Things that make code hard to test

  • Mixing 'new' with logic
  • Looking for things
  • Work in the constructor
  • Global state
  • Singletons
  • Static methods
  • Deep inheritance
  • Mixing service/value

Good Unit Tests

  • Test a single behavior
  • Test each behavior only once
  • Are independent from one another
  • Mock network/database connections
  • Are cheap and easy to maintain

When writing a unit test, read the code to understand the structure and the related issues. Don’t read it to understand the functionality.

Photo by tim caynes

Example

Photo by Stéfan

Untitled Slide