Method was expected to be called 1 times, actually called 0 times.
bartonhammond opened this issue · 2 comments
bartonhammond commented
The "mail" built in function is not getting mocked...Not sure what I'm missing.
Test case:
<?php
namespace Tests;
require_once __DIR__ . "/../../utilities/Util.php";
class UtilTest extends \PHPUnit\Framework\TestCase {
use \phpmock\phpunit\PHPMock;
public function testReportError()
{
$mail = $this->getFunctionMock(__NAMESPACE__, "mail");
$mail->expects($this->once())
->willReturnCallback(
function ($email, $subject, $body) {
print 'inside callback';
var_dump($email);
var_dump($subject);
var_dump($body);
$this->assertEquals("mdahlke@wisnet.com", $email);
$output = ["failure"];
$return_var = 1;
}
);
$result = \Util::reportError('testReportErrorWithNoSubjectSendEmailFails', 'testArg', 'Testing reporting errors', ['subject' => 'test']);
}
}
SUT Util.php
public static function reportError($mailArgs = []) {
print("\nready to call mail");
$result = mail($mailArgs['email'], $mailArgs['subject'], $mailArgs['body']);
print("\nresult " . $result);
return $result;
}
Output
composer test
phpunit --colors=always
PHPUnit 5.7.23 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
ready to call mail
result 1
Time: 59 ms, Memory: 5.00MB
There was 1 failure:
- Tests\UtilTest::testReportError
Expectation failed for method name is equal to string:delegate when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
bartonhammond commented
Argh...just realized the SUT and Testcase both have to share the same namespace...
henryobiaraije commented
Yes, that is correct.
If the SUT is in a different namespace, you can dynamically get the namespace using PHP ReflectionClass.
See here https://stackoverflow.com/a/67696809/6909825