Category : phpunit

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

In my Laravel 8 project, I have this action class: <?php namespace AppActionsContent; use IlluminateSupportFacadesConfig; class FixUriAction { public function __invoke(string $uri) { if (preg_match(‘/^https?:///i’, $uri)) { return $uri; } return ‘/’ . Config::get(‘current_lang’)->code . ‘/’ . $uri; } } I want to write unit tests for this class, now I have this code in ..

Read more

From the Laravel Testing Documentation: # Parallel Testing & Databases Laravel automatically handles creating and migrating a test database for each parallel process that is running your tests. The test databases will be suffixed with a process token which is unique per process. For example, if you have two parallel test processes, Laravel will create ..

Read more

I use bugsnag throughout my application. When writing my unit tests, how can I verify that Bugsnag is being alerted? Since it’s a facade, I assume I should be able to mock like this Bugsnag::shouldReceive("notifyError"); I get this error though Received Mockery_3_Bugsnag_Client::leaveBreadcrumb(), but no expectations were specified I’m not calling leaveBreadCrumb() anywhere in my app. ..

Read more

I’m building a messenger system with Redis publishing on the Laravel end and subscribing on a node server. I would like to test what is stored in the redis pub method using PHPUnit, but I have no idea where to start. Controller class MessageController extends Controller { public function store(Conversation $conversation, Request $request) { $user ..

Read more

I have a class like this: <?php use AppModelsProduct; class ProductSearcher { public function getPrintedProducts( $releasedOnly = true ) { $products = Product::with(‘productVersion’,’productVersion.tag’) ->where(‘printed’, 1); if ($releasedOnly) $products->where(‘released’, 1); $products = $products->get(); return $products; } } In my testing, I write // … some other testing … public function testChossingCorrectingProductFromProductVersionIds() { $productSearcher= new ProductSearcher; $productMock ..

Read more

I write here after many attempts but my problem isn’t solved yet. I want to create a test using PHPUnit on Laravel my class has function described like below: public function test_not_connected_user_can_not_create_new_task(){ $this->withoutExceptionHandling(); //Given we have a task object $task = Task::factory()->make(); //When unauthenticated user submits post request to create task endpoint // He should ..

Read more

I’ve a code for testing create_new_blog, the Blog model has strings data as well as images field which is a list of images. the code for testing is: public function test_create_blog() { $this->withoutExceptionHandling(); $user = User::factory()->create(); $blog = Blog::factory( [‘user_id’ => $user->id] )->make(); $response = $this->post(‘/api/blogs’, $blog->toArray()); $response->assertStatus(201)->assertJson([ ‘status’ => true, ‘message’ => ‘Blog Created’, ..

Read more

I’ve a code for testing create_new_blog, the Blog model has strings data as well as images field which is a list of images. the code for testing is: public function test_create_blog() { $user = User::factory()->create(); $blog = Blog::factory( [‘user_id’ => $user->id] )->make(); $response = $this->post(‘/api/blogs’, $blog->toArray()); $response->assertStatus(201)->assertJson([ ‘status’ => true, ‘message’ => ‘Blog Created’, ‘id’ ..

Read more

How do I inspect the JSON response in the terminal exactly how it would be returned from the ConversationResource? Controller public function show(Conversation $conversation) { $conversation->load(‘participants’); $messages = $conversation ->messages() ->with(‘sender’) ->latest() ->paginate(10); return new ConversationResource($conversation); } Test /** @test */ public function a_user_can_create_conversation_if_one_doesnt_exist() { $this->withoutExceptionHandling(); $this->actingAs($user = User::factory()->create()); $friend = User::factory()->create(); $response = $this->json(‘GET’, ..

Read more

I’d like to test if my mailable is attaching a list of files. Mail::fake(); Storage::disk(‘agency_files’)->assertExists("$agency->AgencyCoID/agreement.pdf"); Mail::assertSent(BrokerFiles::class); In my mailable, I have: return $this->markdown(‘mail.broker_files’) ->attachFromStorageDisk(‘agency_files’, ‘/’.$this->agency->AgencyCoID.’/agreement.pdf’); My question is, how do I assert that the file was attached? Sourc..

Read more

Tell me please. New to Unit tests, writing a test. The application has helpers (App Helpers Helper, ‘Helper’ => App Helpers Helper :: class added to the aliases in the config) For tests, it is necessary to use the functionality of the helpers, since authorization goes through another service, and I send all requests there ..

Read more

I have an Laravel app with about 30 permissions. App also uses plenty of endpoints. Now I want to write feature tests for each endpoint, checking every permission on it. There is my question: Should I write separate method for each permission like that: public function test_if_user_can_create_article_having_articles_index_permission() { $user = $this->makeUserWithSuchPermisssion(); $this->actingAs($user)->post(‘/articles’)->assertStatus(403) } public function ..

Read more

I need to mock a db model that calls the function save(). Test //Setup function $this->jobAccessor = Mockery::mock(JobAccessor::class); $this->job = Mockery::mock(Job::class); $this->app->instance(‘AppModelsJob’, $this->job); $this->app->instance(‘AppDataJobAccessor’, $this->jobAccessor); //testing function $job = new Job([ ‘id’ => 22, ‘user_id’ => 123 ]); $this->jobAccessor->shouldReceive(‘find’) ->with($jobId) ->andReturns($job); $this->job->shouldReceive(‘save’)->once(); code $job = $this->jobAccessor->find($this->portalId); //do stuff with job then save $job->save(); //how do ..

Read more

I’m using Laravel for my project and I’m new to unit/feature testing so I was wondering what is the best way to approach more complicated feature cases when writing tests? Let’s take this test example: public function testSucceedIfConnectAuthorised() { $connection = factory(Connection::class)->make([ ‘sender_id’ => 1, ‘receiver_id’ => 2, ‘accepted’ => false, ‘connection_id’ => 5, ]); ..

Read more

I want to write a unit test for a form post request. public function addForm(SaveFormRequest $request) { $this->servicelayer->addFormDetails($request->validated()); return redirect->route(‘register’); } How can I mock $request->validated(); for a FormRequest class. I trying below like $saveRequest = $this->createMock(SaveFormRequest::class); But I got an error: Error: call to a member function call() on null. Thanks in advance. Source: ..

Read more

Ì got a function that returns a redirect with a success message as follows: public function update(Request $request) { … return redirect()->route(‘my.route’)->with(‘success’, ‘All objects have been updated.’); } I wrote a feature request to test the functionality of this function. public function test_user_can_update() { $response = $this->put(route(‘my.route’), [ ‘value’ => 15 ]); $response->assertStatus(302); $response->assertSessionHasNoErrors(); $this->assertEquals(‘All ..

Read more

How to test the MainClassTest Methods from a ChildClassTest extending it, since the child class will perform the same test scenarios but given with different data Sample of code <?php namespace TestsFeatureModules; use TestsTestCase; class BaseControllerTest extends TestCase { /** * A basic feature test example. * * @return void */ public function test_common_method_for_each_child() { ..

Read more