kodemania's avatar

How to completely pass PhpUnit Risky test

Hello fellows

I hope you guys are doing well, I was facing a bit difficultly in passing phpunit tests.

Let me explain my code

SignupController

class SignupController extends Controller
{

    /**
     * @var UserRepositoryInterface
     */
    private $repository;

    /**
     * @var RedirectServiceInterface
     */
    private $redirectService;

    /**
     * @param UserRepositoryInterface $userRepo
     */
    function __construct(UserRepositoryInterface $userRepo,RedirectServiceInterface $redirectService){
        $this->repository = $userRepo;
        $this->redirectService  =   $redirectService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('auth.signup');
    }


    /**
     * Signs up New User to Our System.
     *
     * @param SignupRequest $request
     * @param RegistrationServiceInterface $registrationService
     * @param UserRepositoryInterface $userRepository
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function doSignup(SignupRequest $request, RegistrationServiceInterface $registrationService, EmailServiceInterface $emailService, UserRepositoryInterface $userRepository){
        try{
            $newRegisteredUser = $registrationService->registerUser($request->all(),$userRepository);

            $emailService->sendWelcomeEmail($newRegisteredUser);

            $messageLangKey = 'auth.welcome';

            return $this->redirectService->redirectToSignup("successMessage",$messageLangKey);
        }
        catch( Exception $e ){

            $logger = new LoggerService();

            $logger->logException($e,"emergency");
        }
    }
}

RegistrationService class

class RegistrationService extends BaseService implements RegistrationServiceInterface
{
    /**
     * Register New User to Repository
     *
     * @param array $columns
     * @param UserRepositoryInterface $userRepository
     * @return mixed User Model
     * @throws Exception
     */
    public function registerUser(array $columns,UserRepositoryInterface $userRepository)
    {
        $userRepository->create($columns);

        return $userRepository->getUser($userRepository->getInsertedUserId());
    }
}

Email Service Class

class EmailService extends BaseService implements EmailServiceInterface
{

    /**
     * Sends Welcome Email to new registered User
     *
     * @param UserModelInterface $user
     * @return mixed
     */
    public function sendWelcomeEmail(UserModelInterface $user)
    {
        Event::fire(new UserSignedUp($user));
    }
}

User Repository Class

<?php

namespace App\Repositories;

use App\Contracts\Models\UserModelInterface;
use App\Contracts\Repositories\UserProfileRepositoryInterface;
use App\Contracts\Repositories\UserRepositoryInterface;
use App\User;
use Exception;
use Illuminate\Support\Facades\Hash;

class UserRepository extends BaseRepository implements UserRepositoryInterface{

    /**
     * @var User Model Object
     */
    protected $model;
    /**
     * @var UserId
     */
    public $userId;

    /**
     * @var UserProfile Model Object
     */
    protected $profile;

    /**
     * UserRepository constructor.
     *
     * @param UserModelInterface|User $user
     * @param UserProfileRepositoryInterface $profile
     */
    function __construct(UserModelInterface $user, UserProfileRepositoryInterface $profile){
        //Parent::__construct($user);
        $this->model = $user;
        $this->profile = $profile;
    }
public function create(array $columns)
    {
        $this->model->username          =   $columns['username'];
        $this->model->password          =   Hash::make($columns['password']);
        $this->model->activate_token    =   Hash::make($columns['email'].str_random(8));

        if(! $this->model->save() ){
            throw new Exception("Error In saving User to Database");
        }

        $this->profile->createUserProfile(array('email' =>  $columns['email']), $this->model);

        $this->userId = $this->model->id;
    }
}

Event Listener

class SendWelcomeEmail implements ShouldQueue
{

    private $mailer;

    /**
     * Create the event listener.
     *
     * @param Mailer $mailer
     */
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Handle the event.
     *
     * @param  UserSignedUp  $event
     * @return void
     */
    public function handle(UserSignedUp $event)
    {
        $user = $event->user;
        $this->mailer->queue('auth.emails.welcome',['user' => $user],function($m) use ($user){
            $m->from('noreply@ismartz.com','Ismartz.com');
            $m->to($user->profile->email, $user->username)->subject('Please Activate your Account');
        });
    }
}

Now This is test I am performing

<?php

use App\Repositories\UserProfileRepository;
use App\Repositories\UserRepository;
use App\Services\RegistrationService;
use App\UserProfile;
use App\User;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Hash;

class SignupTest extends TestCase
{
    use DatabaseTransactions;
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testSignup_process_fresh_user()
    {
        $username = str_random(16)."yousa".time();

        $password = str_random(16);

        $email = $username."@gmail.com";

        $this->visit('signup')
            ->type($username,'username')
            ->type($password,'password')
            ->type($email,'email')
            ->press('signup')
            ->seeInDatabase('users',['username' =>  $username])
            ->seeInDatabase('user_profiles',['email'    =>  $email])
            ->see("Successfully");
    }

    public function testSignup_user_is_registered_before_same_email_case(){

        $userRepo = new UserRepository(new User(),new UserProfileRepository(new UserProfile()));

        $user = $userRepo->getUser(1);

        $this->assertInstanceOf(User::class,$user);

        $this->visit('signup')
            ->type(str_random(16)."yousa",'username')
            ->type(str_random(16),'password')
            ->type($user->profile->email,'email')
            ->press('signup')
            ->see("Error");
    }

    public function testSignup_user_is_registered_before_same_username(){

        $userRepo = new UserRepository(new User(),new UserProfileRepository(new UserProfile()));

        $user = $userRepo->getUser(1);

        $this->assertInstanceOf(User::class,$user);

        $this->visit('signup')
            ->type($user->username,'username')
            ->type(str_random(16),'password')
            ->type(str_random(16)."yousa@gmail.com",'email')
            ->press('signup')
            ->see("Error");
    }
}

All classes are getting injected via laravel IoC. How can I make this code pass test with green. Any Suggestions

0 likes
0 replies

Please or to participate in this conversation.