Slide 1

Slide 1 text

Hidden Secrets of Unit Testing The Long Journey to Writing Tests That Matter

Slide 2

Slide 2 text

What are Unit Tests Unit = Smallest Testable Part of Application In most cases -> methods sometimes -> state of object

Slide 3

Slide 3 text

Input / Output result = Calculator.sumOf 1, 1 expect(result).toBe 2 -------------------------------------------------------- Only tests the output of a method when called with specific parameters.

Slide 4

Slide 4 text

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)

Slide 5

Slide 5 text

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)

Slide 6

Slide 6 text

Three Golden Rules Explicit Dependencies Tell, Don't Ask Listen to Your Tests

Slide 7

Slide 7 text

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?

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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!

Slide 10

Slide 10 text

Thank you! Dominik Guzei @DominikGuzei (Twitter)