kodemania's avatar

Risky Test PhpUnit

Hello guys

Could you help me with risky test. How to write code which passes completely and avoid risky tests.

Regards

0 likes
4 replies
zachleigh's avatar

Show us your risky test. There are several reasons a test can be considered risky.

kodemania's avatar

My controller

<?php

namespace App\Http\Controllers\Auth;

use App\Contracts\Repositories\SocialUserRepositoryInterface;
use App\Contracts\Repositories\UserProfileRepositoryInterface;
use App\Contracts\Repositories\UserRepositoryInterface;
use App\Contracts\Services\EmailServiceInterface;
use App\Contracts\Services\LoggerServiceInterface;
use App\Contracts\Services\RedirectServiceInterface;
use App\Contracts\Services\RegistrationServiceInterface;
use App\Http\Requests\SignupRequest;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Http\Request;
use Illuminate\Session;

use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;

class SignupController extends Controller
{

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

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

    /**
     * @var LoggerServiceInterface
     */
    private $logger;

    /**
     * @var EmailServiceInterface
     */
    private $mailer;

    /**
     * @var UserProfileRepositoryInterface
     */
    private $profileRepository;

    /**
     * @var SocialUserRepositoryInterface
     */
    private $socialRepository;

    /**
     * @param UserRepositoryInterface $userRepo
     * @param RedirectServiceInterface $redirectService
     * @param LoggerServiceInterface $logger
     * @param EmailServiceInterface $mailer
     * @param UserProfileRepositoryInterface $profileRepository
     */
    function __construct(UserRepositoryInterface $userRepo,RedirectServiceInterface $redirectService,LoggerServiceInterface $logger, EmailServiceInterface $mailer, UserProfileRepositoryInterface $profileRepository, SocialUserRepositoryInterface $socialUser ){

        /** UserRepository instance */
        $this->repository = $userRepo;

        /** RedirectService instance */
        $this->redirect  =   $redirectService;

        /** LoggerService instance */
        $this->logger   =   $logger;

        /** Email Service instance */
        $this->mailer   =   $mailer;

        /** UserProfileRepository instance */
        $this->profileRepository    =   $profileRepository;

        /** SocialUserRepository instance */
        $this->socialRepository = $socialUser;
    }

    /**
     * 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
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function doSignup(SignupRequest $request, RegistrationServiceInterface $registrationService){

        $type = 'form';

        try{
            $newRegisteredUser = $registrationService->registerUser($type,$request->all(),$this->repository,$this->profileRepository);
            $this->mailer->sendWelcomeEmail($newRegisteredUser);
            $messageLangKey = 'auth.welcome';
            return $this->redirect->toSignup("successMessage",$messageLangKey);
        }
        catch( Exception $e ){
            $this->logger->logException($e,"emergency");
        }
        $messageLangKey = 'auth.error';
        return $this->redirect->toSignup("failureMessage",$messageLangKey);
    }

    /**
     * redirects user to facebook oAuth api
     *
     * @return mixed
     */
    public function facebookSignup(){
        return Socialite::driver('facebook')->scopes([
            'public_profile',
            'email',
            'user_about_me',
            'user_birthday',
            'user_hometown',
            'user_location',
            'user_website',
            'manage_pages',
            'publish_pages'
        ])->redirect();
    }

    /**
     * Callback function for facebook oAuth api
     * @param RegistrationServiceInterface $registrationService
     * @return mixed
     */
    public function facebookCallback(RegistrationServiceInterface $registrationService){

        try{

            $user = Socialite::driver('facebook')->user();

            $type = 'facebook';

            $columns = array(
                'social'    =>  true,
                'active'    =>  true,
                'username'  =>  implode("",explode(" ",$user->name)),
                'email'     =>  $user->email,
                'name'      =>  $user->name,
                'provider'  =>  $type,
                'token'     =>  $user->token,
            );

            if(isset($user->user["gender"])){
                array_add($columns,"gender", ($user->user["gender"] == "male")? true : false );
            }

            $newRegisteredUser = $registrationService->registerUser($type,$columns,$this->repository,$this->profileRepository,$this->socialRepository);

            $this->mailer->sendWelcomeEmail($newRegisteredUser);

            $messageLangKey = 'auth.welcome';

            return $this->redirect->toSignup("successMessage",$messageLangKey);
        }
        catch(ClientException $e){
            $messageLangKey = 'auth.socialError';
            return $this->redirect->toSignup("successMessage",$messageLangKey);
        }
        catch(Exception $e){
            $this->logger->logException($e,"emergency");
        }

        $messageLangKey = 'auth.error';
        return $this->redirect->toSignup("failureMessage",$messageLangKey);
    }
}

My test for this controller

<?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");
    }


}

if you need more Classes to be shown, Let me know.

zachleigh's avatar

Hmmm.... Run phpunit in verbose mode to see if it tells you the reason.

phpunit -v
kodemania's avatar

it just showing Ok but incomplete, skipped or risky tests

Please or to participate in this conversation.