Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active May 14, 2021 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/6b6ded4c51d5493ca26e7cc1c5b79d61 to your computer and use it in GitHub Desktop.
Save kobus1998/6b6ded4c51d5493ca26e7cc1c5b79d61 to your computer and use it in GitHub Desktop.
test old code using dependency injection
<?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