Summer Sale! All accounts are 50% off this week.

learningneverstop12345's avatar

mocking utility class

is it possible to mock this when doing http test?


namespace App\Utils;

use Twilio\Rest\Client;

class Twilio
{
    const EMAIL_CHANNEL = 'email';
    const SMS_CHANNEL = 'sms';
    const VERIFY_APPROVED = 'approved';

    private static function initialize()
    {
        return new Client(config('twilio.sid'), config('twilio.token'));
    }

    public static function requestOtp(string $recipient, string $channel)
    {
        return self::initialize()
            ->verify
            ->v2
            ->services(config('twilio.services.verify'))
            ->verifications
            ->create($recipient, $channel);
    }
}

in my controller it look something like this

class Controller
{
    public function store(Request $request)
	{
        // some code here...
	    Twilio::requestOtp($request->recipient, $request->channel);
	    // some code here..
	}
}
0 likes
2 replies
Niush's avatar

Looks are you are importing Utils/Twilio class in your controller.

Instead what you want to do is load the Utils/Twilio using Laravel Service Container.

Either in the store function parameter, like this:

public function store(Twilio $twilioUtil)
{
      $twilioUtil::requestOtp(....);
}

Or using app(), like this:

public function store()
{
      $twilioUtil = app(Twilio::class);
      $twilioUtil::requestOtp(....);
}

Then, you can mock the Twilio Class using Mockery. https://laravel.com/docs/9.x/mocking#mocking-objects

If you have a function that returns some value. Or, want to test if passed arguments are correct. Mockery has that covered. https://docs.mockery.io/en/latest/reference/expectations.html

1 like

Please or to participate in this conversation.