Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Hidden Secrets of Unit Testing

Hidden Secrets of Unit Testing

Summary of important aspects and pitfalls of unit testing in any language

dominikguzei

March 23, 2012
Tweet

Other Decks in Programming

Transcript

  1. What are Unit Tests Unit = Smallest Testable Part of

    Application In most cases -> methods sometimes -> state of object
  2. Input / Output result = Calculator.sumOf 1, 1 expect(result).toBe 2

    -------------------------------------------------------- Only tests the output of a method when called with specific parameters.
  3. Peer Communication mock = Controller.create() view = View.create delegate: mock

    view.onDonateButtonClicked() expect(mock.donate).toHaveBeenCalled() -------------------------------------------------------- Tests the protocol / communication between test subject (view) and its dependencies (delegate)
  4. Changed State car = Car.create() expect(car.position).toEqual x: 0, y: 0

    -------------------------------------------------------- car = Car.create() car.moveTo x: 3, y: 4 expect(car.position).toEqual x: 3, y: 4 -------------------------------------------------------- Use only for testing public attributes (models)
  5. Explicit Dependencies class TestView constructor: -> # wrong -> hidden

    / hard dependency @delegate = App.Controller.create() -------------------------------------------------------- class TestView # explicit dependency from outside constructor: (@delegate) -> throw "need delegate" unless @delegate?
  6. Tell, Don't Ask carWindow = CarWindow.create() car = Car.create window:

    carWindow car.window.close() // asking = wrong car.closeWindow() // telling = right! -------------------------------------------------------- Law of Demeter: Principle of Least Knowledge Know only the surface, not the internals
  7. Listen to Your Tests Discover Code / Architecture Smells: •

    Complex test -> method does too much? • Many mocks in test -> too many dependencies? • Dependency can't be mocked -> hard coupling! • Testing state of objects -> Split into classes that work together, test this communication instead • Test are not readable -> The method names should express the specific domain clearly!