Inquisitive's avatar

What is the best way to call service function from Laravel Feature Test

I have a class

class UserService
{
    private UserRepositoryInterface $userRepository;
    private AuthRepositoryInterface $authRepository;

    public function __construct(UserRepositoryInterface $userRepository, AuthRepositoryInterface $authRepository)
    {
        $this->userRepository = $userRepository;
        $this->authRepository = $authRepository;
    }


    public function generateEmailVerificationToken($user): int|JsonResponse
    {
        $token = random_int(000000, 999999);
        $this->authRepository->storeVerifyEmailToken($token, $user);
        return $token;
    }

}

Now, I am testing,

public function test_user_email_verified_successfully()
{
    $user = User::factory()->create();


    //this line giving me issue
    $token = $this->userService->generateEmailVerificationToken($user);


    $rawData = [
      'user' => $user->email,
      'token' => $token
    ];
    $this->apiPost('/email/verify', $rawData)
        ->assertStatus(200)
        ->assertJsonStructure([
            'user' => [
                'id',
                'name',
                'email',
                'role_id',
                'role',
                'permissions',
                'created_at',
                'updated_at',
            ]
        ]);
}

What is the best way to call this generateEmailVerificationToken? I tried by

$service = new UserService();

But this UserService need UserRepositoryInterface and AuthRepositoryInterface

0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You can resolve it from the container like this

$service = resolve(UserService::class);
1 like
martinbean's avatar

@inquisitive If various test cases need that service, then you can resolve it in your setUp method and assign it to a property:

class FooTest extends TestCase
{
    protected $userService;

    protected function setUp(): void
    {
        parent::setUp();

        $this->userService = $this->app->make(UserService::class);
    }

    public function test_user_email_verified_successfully(): void
    {
        // Use $this->userService in your test here...
    }
}
1 like

Please or to participate in this conversation.