RUNNING TESTS IN ISOLATION USING MOCK OBJECTS Alberto Rodriguez Peon IT-PES-PS Motivating example: ai-bs-vm Command-line tool to create Puppetized VMs How to test this? Isolating it with mocks What is a mock, then? A mock is a “stunt double” used in test time to eliminate a single dependency Image from: http://zeroturnaround.com/rebellabs/how-to-mock-up-your-unit-test-environment-to-createalternate-realities/ How does it look like? def test_play(self): # game.play calls game._toss_coin which returns # ‘heads’ or ‘tails’ randomly assert self.game.play(guess=‘heads’) == ‘You win!’ assert self.game.play(guess=‘tails’) == ‘You lose!’ This test case is broken How does it look like? import mock @patch.object(Game, ‘_toss_coin’, return_value=‘heads’) def test_play(self): # game.play calls game._toss_coin which returns # ‘heads’ or ‘tails’ randomly assert self.game.play(guess=‘heads’) == ‘You win!’ assert self.game.play(guess=‘tails’) == ‘You lose!’ What should I mock? Every operation which: Is slow (A query to a database) Is non-deterministic (Obtaining the current date and time) Can trigger hard to reproduce results (A timeout) Take-away message Mocking makes possible to test untestable code by isolating it from its dependencies
© Copyright 2025 Paperzz