samirapadidar's avatar

Write test for service with Mock

I want to write a test for the service, but I need to simulate user login. this is my service method

public function sendMessage(int $ticket_id, array $data): RedirectResponse
    {
        $admin = \Illuminate\Support\Facades\Auth::user();
        $data['ticket_id'] = $ticket_id;
        $res = $this->ticket_message->createTicketMessage(messageable: $admin, data: $data);
        event(new TicketMessageCreated(ticket_id: $ticket_id, operator_id: $admin->id));
        if (!$res) {
            return redirect()->back()->with('error', 'ticket_type cant create ');
        }
        return redirect()->back()->with('message', 'ticket_type update succesfully');
    }

this path: app/Services/TicketMessageService.php

and this is my test

public function testSendMessage(): void
    {
        $ticket_messsage_temp = $this->makeFakeTicketMessageInDb();//This create one ticket message
        $this->assertInstanceOf(TicketMessage::class, $ticket_messsage_temp);
        $data = $this->makeFakeDataTicketMessage();//this create an array
        $result = $this->massage_service->sendMessage(ticket_id: $ticket_messsage_temp->id, data: 
         $data);//This method is for my service

        $this->assertInstanceOf(RedirectResponse::class, $result);
        $this->assertEquals(302, $result->getStatusCode());
    }

this path: tests/Services/TicketMessageServiceTest.php

when run this test say $admin in null, it should be App\Models\HasTicketMessageInterface From this I understand that I have to simulate the user's login, but I don't know how

how to solve this problem???????

pleas help me

0 likes
4 replies
tykus's avatar

@samirapadidar you can put it at the top of the test like this:

public function testSendMessage(): void
{
    $this->actingAs(User::factory()->create());
    $ticket_messsage_temp = $this->makeFakeTicketMessageInDb();//This create one ticket message
    // ... etc
1 like
tykus's avatar

You can simulate an authenticated session using the actingAs method, e.g.

$this->actingAs($user);

How you create a User instance for the test is up to you; it could be a Factory, or just new up a User instance if that is sufficient.

Please or to participate in this conversation.