Slide 1

Slide 1 text

Travesty of a Mockery...

Slide 2

Slide 2 text

Travesty of a Mockery... » @davedevelopment » CTO at Childcare.co.uk » Podcaster at ThatPodcast.io

Slide 3

Slide 3 text

Terminology -- http://xkcd.com/503/

Slide 4

Slide 4 text

Terminology

Slide 5

Slide 5 text

Dependencies $doc = new UserRepository(); $sut = new UserService($doc);

Slide 6

Slide 6 text

Test Doubles A replacement for a real dependency, used to enable, ease or improve testing of the SUT $double = new NullUserRepository(); $sut = new UserService($double);

Slide 7

Slide 7 text

Creating Test Doubles

Slide 8

Slide 8 text

Hand built

Slide 9

Slide 9 text

Generated

Slide 10

Slide 10 text

Generated Doubles: Tools » phpunit/phpunit-mock-objects » phpspec/prophecy » mockery/mockery » phake/phake » codeception/aspect-mock » php-vcr/php-vcr » many others...

Slide 11

Slide 11 text

Configurable

Slide 12

Slide 12 text

Test Doubles » Dummy » Fake » Stub » Mock » Spy

Slide 13

Slide 13 text

Dummies

Slide 14

Slide 14 text

Dummies Used whenever we need to pass arguments to a constructor or method, where those arguments should not be used while exercising the SUT

Slide 15

Slide 15 text

Dummies: Values # SUT BCryptPasswordEncoder public function encodePassword($raw, $salt) { if ($this->isPasswordTooLong($raw)) { throw new BadCredentialsException( 'Invalid password.' ); } # ... }

Slide 16

Slide 16 text

Dummies: Values /** @test */ public function it_refuses_a_long_password() { $encoder = new BCryptPasswordEncoder(31); $this->setExpectedException( "BadCredentialsException" ); $encoder->encodePassword( str_repeat("a", 4097), "dummy salt that will not be used" ); }

Slide 17

Slide 17 text

Dummies: Objects # SUT AuthenticationProvider public function __construct(EncoderInterface $encoder) { $this->encoder = $encoder; } public function checkAuthentication(User $user, $presentedPassword) { if ("" === $presentedPassword) { throw new BadCredentialsException( 'The presented password cannot be empty. '); } # do something with the encoder }

Slide 18

Slide 18 text

Dummies: Objects by hand class DummyEncoder implements EncoderInterface { public function isPasswordValid($hashedPassword, $plainTextPassword, $salt) { throw new RuntimeException("Not implemented"); } }

Slide 19

Slide 19 text

Dummies: Objects by hand /** @test */ public function it_throws_on_an_empty_password() { $authProvider = new AuthenticationProvider( new DummyEncoder() ); $this->setExpectedException("BadCredentialsException"); $authProvider->checkAuthentication(new User(), ""); }

Slide 20

Slide 20 text

Dummies: Objects with mockery /** @test */ public function it_throws_immediately_on_an_empty_password() { $authProvider = new AuthenticationProvider( Mockery::mock("EncoderInterface") ); $this->setExpectedException("BadCredentialsException"); $authProvider->checkAuthentication(new User(), ""); }

Slide 21

Slide 21 text

Fakes

Slide 22

Slide 22 text

Fakes "Replace a component that the system under test (SUT) depends on with a much lighter-weight implementation." -- http://xunitpatterns.com We use a Fake whenever our SUT has a dependency that is unavailable, slow or simply makes testing difficult.

Slide 23

Slide 23 text

Fakes: Fake Object class PlaintextPasswordEncoder extends BasePasswordEncoder { public function encodePassword($raw, $salt) { return sprintf("%s{%s}", $raw, $salt); } }

Slide 24

Slide 24 text

Fakes: Fake Object /** @test */ public function it_validates_a_password() { $encoder = new PlaintextPasswordEncoder(); $authProvider = new AuthenticationProvider($encoder); $user = new User([ 'password' => 'pass{salt}', 'salt' => 'salt' ]); $this->assertNull( $authProvider->checkAuthentication($user, "pass") ); }

Slide 25

Slide 25 text

Fakes » Usually hand coded » Low coupling between SUT and test » May need to expose state for verification » Can get complicated to maintain

Slide 26

Slide 26 text

Stubs

Slide 27

Slide 27 text

Stubs Stubs are used to control the indirect inputs to the SUT, by providing canned responses to calls made during the test

Slide 28

Slide 28 text

Stubs: Stub Object /** @test */ function it_gets_a_user() { $employee = new Employee(); $repo = $this->getMock('EmployeeRepository'); $repo->method('find') ->with($id = 123); ->willReturn($employee); $sut = new UserService($repo); $this->assertEquals( $employee, $sut->get($id) ); }

Slide 29

Slide 29 text

Mocks

Slide 30

Slide 30 text

Mocks Mocks are used to verify the indirect outputs of the SUT

Slide 31

Slide 31 text

Mocks: Example /** @test */ function it_persists_a_user() { $employee = new Employee(); $repo = $this->prophesize('EmployeeRepository'); $repo->add($employee)->shouldBeCalled(); $sut = new UserService($repo->reveal()); $sut->post($employee); $this->getProphet()->checkPredictions(); }

Slide 32

Slide 32 text

Mocks: Example /** @test */ function it_persists_a_user() { $employee = new Employee(); $repo = $this->prophesize('EmployeeRepository'); $repo->add($employee)->shouldBeCalled(); $sut = new UserService($repo->reveal()); $sut->post($employee); }

Slide 33

Slide 33 text

Mocks » Verify behaviour of the SUT by requiring you to provide details of any interaction they should expect » Can act as stubs, returning values » Can lead to overspecification, leading to brittle tests

Slide 34

Slide 34 text

Mocks: When to use them » When you need to verify the behaviour of the SUT, because it's not easy to do so via the final state of the SUT » When you're working outside-in, discovering new interfaces as you develop the SUT

Slide 35

Slide 35 text

Spies

Slide 36

Slide 36 text

Spies Spies are used to observe the indirect outputs of the SUT

Slide 37

Slide 37 text

Spies: Example /** @test */ function it_persists_a_user() { $employee = new Employee(); $repo = $this->prophesize('EmployeeRepository'); $repo->add($employee)->shouldBeCalled(); $sut = new UserService($repo->reveal()); $sut->post($employee); }

Slide 38

Slide 38 text

Spies: Example /** @test */ function it_persists_a_user() { $employee = new Employee(); $repo = $this->prophesize('EmployeeRepository'); $sut = new UserService($repo->reveal()); $sut->post($employee); $repo->add($employee)->shouldHaveBeenCalled(); }

Slide 39

Slide 39 text

Spies » Record interactions, allow verification afterwards » More familiar workflow: Arrange -> Act -> Assert Given -> When -> Then » Can reveal more intent, by hiding irrelevant calls » Less likely to expose smells by hiding details » Less precise, leading to less fragile tests » Debugging can be harder

Slide 40

Slide 40 text

Spies: When to use them (instead of mocks) » If you would like to » To help communicate the intentions of your test » If you can't predict a value ahead of time » If a mock wouldn't be able to report a failed expectation (edge case)

Slide 41

Slide 41 text

Considerations

Slide 42

Slide 42 text

Test First or Test Last

Slide 43

Slide 43 text

State or Behaviour

Slide 44

Slide 44 text

Classicist vs Mockist

Slide 45

Slide 45 text

Verifiying State “We inspect the state of the SUT after it has been exercised and compare it to the expected state.” Verifying Behaviour “We capture the indirect outputs of the SUT as they occur and compare them to the expected behavior.”

Slide 46

Slide 46 text

Behaviour Verification: Precision “Following Einstein, a specification should be as precise as possible, but not more precise” -- Mock Roles, not Objects Find a balance between precision and flexibility. Greater precision leads to over-specified, brittle tests. Allow Queries, expect Commands Ignore collaborators that are irrelevant for the current test

Slide 47

Slide 47 text

Behaviour Verification Mock all the things? 16 Mock objects 18 method expectations

Slide 48

Slide 48 text

When to mock “Never mock values, sometimes mock entities, but mock services freely.” » http://blog.thecodewhisperer.com/2010/09/14/when- is-it-safe-to-introduce-test-doubles

Slide 49

Slide 49 text

When to Mock: Don't mock values Just create them. $email = m::mock("Email"); $email->shouldReceive("getDomain")->andReturn("example.com"); $email = Email::fromString("[email protected]");

Slide 50

Slide 50 text

When to Mock: Try not to mock concrete classes » It hides relationships between objects » A form of over-specification » If describing an interface doesn't seem right, don't use a test double $employee = m::mock("Employee"); $employee->shouldReceive("getEmail")->andReturn("[email protected]"); # use object mothers or test data builders for complicated object graphs etc $employee = ExampleEmployee::withEmail("[email protected]");

Slide 51

Slide 51 text

When to Mock: Only mock types you own » Or try to only mock types you trust » Use mocking to derive interfaces for the things your SUT needs » Write adapters for the things you don't trust

Slide 52

Slide 52 text

When to Mock: Mock Ports

Slide 53

Slide 53 text

Questions/Feedback » joind.in/14900 » @davedevelopment » [email protected]