Last active
May 14, 2021 13:30
-
-
Save kobus1998/6b6ded4c51d5493ca26e7cc1c5b79d61 to your computer and use it in GitHub Desktop.
test old code using dependency injection
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 | |
interface Dep { | |
public function has(); | |
} | |
// i want to test this function and get 100% code coverage | |
function depends(Dep $dependency) { | |
if ($dependency->has()) { | |
return true; | |
} | |
return false; | |
} | |
// my actual class always returns true and i can't change this behaviour | |
class MyRealClass implements Dep | |
{ | |
public function has() | |
{ | |
return true; | |
} | |
} | |
// mock the class returning false | |
$mockFalse = new class implements Dep { | |
public function has() | |
{ | |
return false; | |
} | |
}; | |
$bTest = false; | |
if (depends($mockFalse) === false) { | |
$bTest = true; | |
} | |
echo ($bTest ? 'test succeeded' : 'test failed') . "\n"; | |
// mock the class returning true | |
$mockTrue = new class implements Dep { | |
public function has() | |
{ | |
return true; | |
} | |
}; | |
$bTest = false; | |
if (depends($mockTrue) === true) { | |
$bTest = true; | |
} | |
echo ($bTest ? 'test succeeded' : 'test failed') . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment