Skip to content

Method was expected to be called 1 times, actually called 0 times. #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
bartonhammond opened this issue Oct 18, 2017 · 2 comments
Closed

Comments

@bartonhammond
Copy link

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:

  1. 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
Copy link
Author

Argh...just realized the SUT and Testcase both have to share the same namespace...

@henryobiaraije
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants