Category : mockery

I am using mockery/mockery to mock laravel db facade on my unit test. But I don’t know how to create a stub for the when method. So here is my class that I want to test. <?php namespace App; use IlluminateSupportFacadesDB; class TestRepo { public function testQb() { DB::table(‘users’) ->when(true, function($query) { $query->where(’email_verified_at’, null); }) ..

Read more

I am using phpunit and Laravel. I need to test the routes of a controller that uses TwilioRestClient and I am stuck at the create function! This is the general code of the create function that gives me problems: public function create(Request $request) { //some code $twilioAccount = $this->twilioClient->api->v2010->accounts->create($account_options); $this->twilioClient = new Client($twilioAccount->sid, $twilioAccount->auth_token); $apiKey ..

Read more

I have the following Test Setup. The Employee model has 1..n EmployeeVersions. I want to mock only the vacationBalance method. The $employee model has already needed values as attributes at this point so I would like to keep those values. $employee = $this->createFullEmployee(employee_version_data: [ ‘avg_week_hours’ => 4200, ‘working_percentage’ => 100, ‘wage’ => 4000, ‘yearly_vacations_entitlement’ => ..

Read more

I’m trying to mock the Auth facade so I can mock the Auth::user() method. I need this because I source my users from another database. In production, this all works fine. However, when I try and write tests for this and try something like; $user = User::factory()->create(); Auth::shouldReceive(‘user’)->andReturn($user); $response = $this->postJson(route(‘api.login’), [ ‘username’ => ‘username’, ..

Read more

I’m trying to use Laravel’s app service container to resolve out mocked instances for testing. I’ve created a mock which works when making an instance of CS_REST_Subscribers alone, however if I provide arguments to the service container my mock no longer applies. $this->mock(CS_REST_Subscribers::class, function (MockInterface $mockery) { $mockery ->shouldReceive(‘add’) ->once(); }); get_class(app()->make(CS_REST_Subscribers::class)); // returns Mockery_2_CS_REST_Subscribers ..

Read more

I am currently unit testing some of my form validation and need to mock a route parameter so that it can pass the tests. I’ve set up what I thought was the right expectation for the request but I’ve not done something correctly. Rule::unique(‘users’)->ignore($this->route(‘user’)->id) This is the test mock that I’m attempting to get to ..

Read more

I have a simple function that cleans strings imported from a CSV. It is a method on a Laravel service, and I am using it in a console command I am testing. class myService implements MyServiceInterface { public function cleanString($string) { if(is_null($string)) return $string; return preg_replace(‘/[^A-Za-z0-9 [email protected]#$%^&*()\|’";:]/’, ”, $string); } } I have several other ..

Read more

I have some class that creates user "integration" and check API credentials using external API: class IntegrationService { public function create(array $params) { $api = new IntegrationApi(); if (!$api->checkCredentials($params[‘api_key’])) { throw new Exception(‘Invalid credentials’); } // storing to DB return ‘ok’; // just for example } } IntegrationApi class: class IntegrationApi { public function checkCredentials(string ..

Read more

I’m trying to mock a method in the Model so that I am able to test the controller api endpoint with different scenarios. I am currently using Laravel 8 with PhpUnit and Mockery package. In the route I am using Route model binding. api.php Route::get(‘/api/{project}’, [ProjectController::class, ‘show’]); ProjectController.php class ProjectController extends Controller { public function ..

Read more

I have this class that push data to multiple urls using Http::Pool. class Pusher() { public function __construct($data, $headers) { $this->data = $data; $this->headers = $headers; } public function pushToAddresses() { $addresses = get_address_somewhere_here(); $responses = Http::pool(fn (Pool $pool) => $addresses->map(fn ($address) => $this->pushData($pool, $address))); } public function pushData(Pool $pool, $address) { return $pool->withHeaders($this->headers) ->withBody($this->data, ..

Read more

I have model method public static function getDetails( array $fields, array $where_condition ) { return Event::select($fields) ->where($where_condition)->first(); } I am calling this method like this $logo = Event::getDetails( [‘logo’], [‘id’ => $id] )->logo; so what I tried to mock method in below way but not working $mock = $this->mock(Event::class, function (MockInterface $mock) { $collection = ..

Read more

I’m trying to use overload option of Mockery library on Laravel 5. I write this test case: <?php namespace TestsUnit; use Mockery; use TestsTestCase; /** * @runTestsInSeparateProcesses * @preserveGlobalState disabled */ class RenewSignatureTest extends TestCase { public function testHandle() { /** @var mixed $mock */ $mock = Mockery::mock(‘overload:AppFooClass’); $mock->shouldReceive(‘callBar’)->times(2); } } According to documentation, this ..

Read more

I am trying to create a mockery unit test but it giving me this error This test did not perform any assertions public function testGetById() { $mock = Mockery::mock(PostService::class)->makePartial(); $mock->shouldReceive(‘getById’) ->withSomeOfArgs(1); $mock->getById(1); } ! get by id→ This test did not perform any assertions testsUnitPostControllerTest.php:30 Tests: 1 risked Time: 0.32s Warning: TTY mode is not ..

Read more

I’m trying to mock a function that will be called by another one. example class TestClass { private static function foo(){ return false } public static function bar() { return self::foo() } } I tried like this $TestClassMock = Mockery::mock(TestClass::class)->shouldAllowMockingProtectedMethods()->makePartial(); $TestClassMock->shouldReceive(‘foo’)->andReturnTrue(); $this->assertEqual($TestClassMock::bar(),true); But it doesn’t work the function is not moocked yet if I use ..

Read more

I mocked the laravel DB facade and my assert passed but mockery complains you didn’t assert DatabaseManager::connection() which i don’t need. DB::partialMock()->shouldReceive(‘table->where->first’)->andReturn((object) [ ‘id’ => 2, ‘name’ => ‘Alex’ ]); But i’ll got this : MockeryExceptionBadMethodCallException : Received Mockery_1_Illuminate_Database_DatabaseManager::connection(), but no expectations were specified Sourc..

Read more

I have the following middleware to update the user’s last_seen_at field and I’ve used it only for routes that an authenticated user can call it: // app/Http/Middleware/LastSeen.php public function handle($request, Closure $next) { $user = $request->user(); $user->last_seen_at = now(); $user->save(); return $next($request); } // app/Http/Kernel.php protected $routeMiddleware = [ // other middleware ‘lastseen’ => AppHttpMiddlewareLastSeen::class ..

Read more

Hello I’m trying to mock a query like this with mockery but I’m not sure how to mock the anonymous function parts: // $this->stores is a IlluminateDatabaseEloquentModel $this->stores->where(‘a’, $a) ->when($b, function ($q) use ($title) { return $query->where(‘title’, $title); }) ->when($name, function ($q) use ($name) { return $query->where(‘name’, $name); }) ->orderBy(‘date’) ->orderBy(‘name’) ->get(); My mock for ..

Read more

Here is my situation. I have this test UpdateAdditionalCommandHandlerTest which is a test for UpdateAdditionalCommandHandler And here is the code: class UpdateAdditionalCommandHandler implements CommandHandler { use DispatchableTrait; use ValidationCommandBus; /** * @var AdditionalRepository */ protected $repository; /** * @param AdditionalRepository $repository */ public function __construct(AdditionalRepository $repository) { $this->repository = $repository; } /** * @param UpdateAdditionalCommand ..

Read more

I am developing a system using Laravel 7.28.4 In the system I have created a SMSService to be able to send SMS message, below is the SMSService code https://codeshare.io/aYjDRM as the code above contains code from configuration i attached the source for the config staticdata file and the .env file https://codeshare.io/5N8lgm https://codeshare.io/aVLAB4 i also attached ..

Read more

I have this class: <?php namespace AppHttpControllersAlerts; use AppHttpControllersController; use AppModelsAlert; use AppModelsFiredAlert; use AppModelsUnitReport; use AppNotificationsAlertSetup; use CarbonCarbon; use IlluminateHttpRequest; use IlluminateSupportFacadesNotification; class AlertController extends Controller { /** * @param Alert $alert * @param null $schema */ public static function checkForInactivity(Alert $alert, $schema = null): void { …some code… } /** * Get int ..

Read more