Last active
August 6, 2021 13:03
-
-
Save eriktorsner/bddfaf7756d66d22df463507d703cc93 to your computer and use it in GitHub Desktop.
test dependencies example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Item_handler { | |
public static function upload_one() { | |
// Do something expensive with lots of deps | |
return true; | |
} | |
public function upload_two() { | |
// Do something expensive with lots of deps | |
return true; | |
} | |
} | |
class Filter_handler { | |
public function __construct( $item_handler = null ) { | |
$this->item_handler = $item_handler; | |
} | |
public function handle_new_avatar() { | |
// This is a hard dependency on Item_handler | |
return Item_handler::upload_one(); | |
} | |
public function handle_new_avatar_testable() { | |
return $this->item_handler->upload_two(); | |
} | |
} | |
// Tests | |
class Mock_Item_Handler() { | |
public function __construct( $data ) { | |
$this->data = $data; | |
} | |
public function upload_two() { | |
return $this->data; | |
} | |
} | |
class Filter_handler_Test() extends Test_Case { | |
public function test_upload() { | |
// Since handle_new_avatar() has a hard dependency on Item_handler, this test will | |
// also execute code in Item_handler::upload_one() and becomes dependant on any set up | |
// requirements it may have. | |
$filter_handler = new Filter_handler(); | |
$this->assertTrue( $filter_handler->handle_new_avatar() ); | |
// Testing Filter_handler::handle_new_avatar_testable() is easier because we can inject a mock object | |
// that allows us to focus on the logic in the function under test rather than worrying about | |
// its depdencencies. | |
// | |
// Chain of dependencies is broken. Testing the Item_handler class isn't affected much by prefering instance | |
// methods over static ones, but testing anything that uses the Item_handler is made easier. | |
$mock_return_data = true; | |
$mock = new Mock_Item_Handler( $mock_return_data ); | |
$filter_handler = new Filter_handler( $mock ); | |
$this->assertTrue( $filter_handler->handle_new_avatar_testable() ); | |
$mock_return_data = false; | |
$mock = new Mock_Item_Handler( $mock_return_data ); | |
$filter_handler = new Filter_handler( $mock ); | |
$this->assertFalse( $filter_handler->handle_new_avatar_testable() ); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment