vendredi 21 juin 2019

Possible to mock model method output in Laravel / PHPUnit?

Is it possible to mock or fake the output of a model method in Laravel 5.8?

For example, consider this model

class Website extends Model
 {
     public function checkDomainConfiguration($domain): bool
     {
         try {
             $records = dns_get_record($domain, DNS_A);
         } catch (ErrorException $e) {
             return false;
         }

         if (isset($records[0]['ip']) && $records[0]['ip'] === $this->server->ipv4_address) {
             return true;
         }

         return false;
     }
 }

for the purpose of the test, I need to tell phpunit that when this method fires (it is called in the controller), to return true, or false if I purposely want it to fail. In the test I factory up a website, and of course it will fail the php method dns_get_record.

I've read the Laravel docs, and scoured google about mocking model methods, but can't seem to find anything, short of wrapping a big if around the method that checks if i'm not in testing mode, and if i am just return true. <-- YUK.

Aucun commentaire:

Enregistrer un commentaire