i must press enter on running tests using phpunit in laravel - laravel

i must press enter on running tests using phpunit in Laravel 5.7.
On every test i get following Message:
1) Tests\Feature\DepartmentsTest::a_admin_can_create_a_department
Mockery\Exception\BadMethodCallException: Received
Mockery_1_Illuminate_Console_OutputStyle::askQuestion(), but no
expectations were specified
by setting following to false, the error disappear:
public $mockConsoleOutput = false;
After that the window hangs on running the test suite and i need to press enter to run the tests.
How can i fix that?
I´am using Windows 10 + PHPUnit 7.5.1 and Laravel 5.7.19
Thanks in advance!
/** #test */
public function a_admin_can_create_a_department()
{
// $this->withoutExceptionHandling();
$attributes = [
'description' => 'Service',
'accessible_by_depart' => true
];
$this->post('/tools/api/storeDepartment', $attributes);
$this->assertDatabaseHas('departments', $attributes);
}

This fixed the problem for me
https://stackoverflow.com/a/48303288/2171254
After doing that, I didn't need the line public $mockConsoleOutput = false;
Greetings

So now I finally found the solution.
On my migration from Laravel 5.1 to Laravel 5.2 (a long time ago) i forgot to add the following lines to the config/app.php File:
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
Now everything works fine.
Greetings Daniel

Related

"ReflectionException Function () does not exist" when trying to setup authentication in Laravel

I'm having some trouble getting authentication working 100% in Laravel (all views seem to work so far except for "home") and was hoping to get some assistance from the Laravel experts out there.
A bit of background info:
PHP Version: 7.3.11
Laravel Version: 8.13.0
Used Composer to build the ui scaffolding (composer require laravel/ui)
Used the Bootstrap ui option (php artisan ui bootstrap --auth)
The issue
As mentioned above, I seem to be able to access all of the generated authentication views so far (login, register & the password reset views), however after registering with a dummy account I get the following error when trying to access the "home" view:
ReflectionException
Function () does not exist
The Stack trace is pointing to the following file:
"vendor/laravel/framework/src/Illuminate/Routing/RouteSignatureParameters.php:23":
<?php
namespace Illuminate\Routing;
use Illuminate\Support\Reflector;
use Illuminate\Support\Str;
use ReflectionFunction;
use ReflectionMethod;
class RouteSignatureParameters
{
/**
* Extract the route action's signature parameters.
*
* #param array $action
* #param string|null $subClass
* #return array
*/
public static function fromAction(array $action, $subClass = null)
{
$parameters = is_string($action['uses'])
? static::fromClassMethodString($action['uses'])
: (new ReflectionFunction($action['uses']))->getParameters();
return is_null($subClass) ? $parameters : array_filter($parameters, function ($p) use ($subClass) {
return Reflector::isParameterSubclassOf($p, $subClass);
});
}
/**
* Get the parameters for the given class / method by string.
*
* #param string $uses
* #return array
*/
protected static function fromClassMethodString($uses)
{
[$class, $method] = Str::parseCallback($uses);
if (! method_exists($class, $method) && Reflector::isCallable($class, $method)) {
return [];
}
return (new ReflectionMethod($class, $method))->getParameters();
}
}
With the following line (line 23) being highlighted as the error:
: (new ReflectionFunction($action['uses']))->getParameters();
And here are the routes used in the "web.php" file:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome', ['pageTitle' => 'Home']);
});
Route::get('/services', function () {
return view('services', ['pageTitle' => 'Services']);
});
Route::get('/contact', function () {
return view('contact', ['pageTitle' => 'Contact']);
});
Auth::routes();
Route::get('/home', ['pageTitle' => 'Client Dashboard'], [App\Http\Controllers\HomeController::class, 'index'])->name('home');
After a bit of googling I've learnt that the method I'm trying to use to setup authentication has been deprecated and it is now advised to use Jetstream or Fortify, however I also found a few examples of people still managing to use this old method in their projects:
https://www.youtube.com/watch?v=NuGBzmHlINQ
As this is my first ever Laravel project I was really trying to just stick with the basics and not over complicate things for myself which is why I chose not to use Jetstream or Fortify and tried to stick to this older approach of setting up authentication. However I've been stuck on this for a couple of hours now and have not been able to figure out what's going wrong which is why I'm now seeking some help with it.
Happy to provide extra details/project code if needed - any help I can get with this would be really appreciated.
Btw, this also happens to be my first ever post on StackOverflow so any feedback on my question or advice on how I can improve it would also be greatly appreciated.
Cheers,
adb
Adjust your last route to include some type of 'action', by removing that second argument (as it only takes 2 arguments):
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
I have changed the web.php file.
I was getting the same error when using the following route:
Route::post('/delete/{id}',[AdminController::class],'destroyProduct');
Changing the route using this code fixed the problem:
Route::post('/delete/{id}','App\Http\Controllers\AdminController#destroyProduct');
I was getting the same error when making a simple route.
Route::get("/test", [ListPagesController::class, "index"]);
This was my code in the web.php file and I was routing my blade file in views via the controller.
When I later redirected it directly to web.php this way without using a controller, the problem was resolved.
Route::get("/test", function () {return view("main");});
I don't quite understand why but the problem is solved.
You Should add it in line 2 web.php
use App\Http\Controllers\YourControllerName;
For me, I changed:
Route::get('/branch/', [Controller::class, 'get_branch_list'])->name('branch');
To:
Route::get('/branch/', 'Controller#get_branch_list')->name('branch');

Laravel Dusk test error on Algolia Search: Impossible to connect, please check your Algolia Application Id

In this project we use Algolia Search installed through Composer. When I'm running a dusk test on the login form it fails because of an error. The login on the form itself performs wel, it seems when this test actually logs in and ends up on the homescreen, this is where it fails.
Note: There is an Algolia APP_ID and SECRET defined in the .env file, and all is working fine when using the application.
The actual error output for this test:
1) Tests\Browser\LoginTest::testLogin
Algolia\AlgoliaSearch\Exceptions\UnreachableException: Impossible to connect, please check your Algolia Application Id.
Dusk test:
public function testLogin()
{
$user = factory(User::class)->create([
'email' => 'dusktester#mail.com',
'password' => '***'
]);
$this->browse(function (Browser $browser) use ($user) {
$browser->visit('/login')
->type('email', 'dusktester#mail.com')
->type('password', '***!')
->press('.button')
->assertPathIs('/');
});
}
Solved it another way. Our login system is a little more complex and links another table depending on the type of user you are. Since this wasn't defined in my user factory within this Dusk test it lacked some crucial information about this user which led to the Algolia Search error.
The way I solved it:
No longer creating a user within the Dusk test and use one of my already seeded test users. The credentials for this user are taken from my .env file to ensure a clean / safe dusk test file that can be uploaded to Git:
public function testLogin()
{
$this->browse(function (Browser $browser){
$browser->visit('/login')
->type('email', env('DUSK_USER'))
->type('password', env('DUSK_PASSWORD'))
->press('.button')
->assertPathIs('/');
});
}

testing in Laravel 5.5 : Class env does not exist

i am starting tests in laravel
i created a ".env.testing" file with this
APP_NAME=myApp
APP_ENV=testing
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://myApp.localhost
DB_CONNECTION=sqlite_testing
i added this in the "connections" part of config/database.php file
...
'sqlite_testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
...
in the phpunit.xml file, i added :
<env name="DB_CONNECTION" value="sqlite_testing" />
and i created a UserTest feature :
class UserTest extends TestCase
{
public function setUp()
{
parent::setUp();
Artisan::call('migrate');
Artisan::call('db:seed');
}
public function tearDown()
{
parent::tearDown();
Artisan::call('migrate:reset');
}
public function testCanAccessUserSpace()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)
->get('/home');
$response->assertStatus(200);
}
}
But when i run the tests, i have this :
ReflectionException: Class env does not exist
What's wrong with my config ?
thanks
I had same error while running the phpunit:
ReflectionException: Class env does not exist
Here was another problem, I've installed package telescope and phpunit tried to load it while testing:
ReflectionException: Class env does not exist
/var/www/html/mat2/vendor/laravel/telescope/src/Telescope.php:263
/var/www/html/mat2/vendor/laravel/telescope/src/Telescope.php:222
and so on.
I've added to phpunit.xml:
<env name="TELESCOPE_ENABLED" value="false"/>
Afterwards, tests are running fine.
So, it may be package testing related error.
If you are using php artisan test --env=testing, add TELESCOPE_ENABLED=false to your .env.testing file and run php artisan config:cache --env=testing.
In my case, set TELESCOPE_ENABLED to false doesn't solve my problem. I have to issue
php artisan config:clear
I use Laravel 7.
Looks like this exception is thrown for a variety of reasons. In your case the issue is with the tearDown function, in specific order of operations within this function. You should call the parent tearDown at the bottom. So this:
public function tearDown()
{
parent::tearDown();
Artisan::call('migrate:reset');
}
Should be refactored as follows:
public function tearDown()
{
Artisan::call('migrate:reset');
parent::tearDown();
}
I suspect the reason is that the app instance gets destroyed inside Illuminate\Foundation\Testing\TestCase. here is the code from Laravel 5.5:
if ($this->app) {
foreach ($this->beforeApplicationDestroyedCallbacks as $callback) {
call_user_func($callback);
}
$this->app->flush();
$this->app = null;
}
This error can be caused by telescope being turned on in a unit testing environment.
I change the default behaviour of telescope to be off and explicitly turn it on in my .env file.
You can change the default to false for telescope by updating your config/telescope.php file.
/*
|--------------------------------------------------------------------------
| Telescope Master Switch
|--------------------------------------------------------------------------
|
| This option may be used to disable all Telescope watchers regardless
| of their individual configuration, which simply provides a single
| and convenient way to enable or disable Telescope data storage.
|
*/
'enabled' => env('TELESCOPE_ENABLED', false), // Change from true to false here.
You will then have to set: TELESCOPE_ENABLED=true in your .env file. This will ensure that you don't have it accidentally turned on in environments you don't want such as production and unit testing.
Might be a bit late for a reply, but the below line in phpunit.xml solved the issue.
<server name="TELESCOPE_ENABLED" value="false"/>
I faced this issue and found issue in config folder > constants file
I was wrote "asset('/')" function in config file, we can't write such functions in config.
Hope this answer will help someone who stuck like this errors.
You need to rename .env.testing to .env, you already set APP_ENV to testing so there is no need to change your .env to .env.testing
EDIT:
Also try to update your dependencies with composer update and try again, it's not a usual bug, so it's something related to your setup of testing environment
I have the same problem in my config/services.php file, my error was calling the route() method in array. I just removed the method and back to works.
For laravel version 8 change app()->environment() to env('ENV_NAME') like
env('SMS_SERVICE_ENDPOINT')
Example:
Previous: app()->environment() === 'production'
New Format should be env('DEV_ENV') === 'production')
Note: Don't forget to add DEV_ENV=production in your .env file
In laravel 8, don't try to use laravel global helper function or Facade after TestCase::tearDown:
class MyTestCase extends TestCase
{
public function tearDown(): void
{
parent::tearDown();
// This will case this exception: Target class [env] does not exist
echo app()->environment();
}
}
Instead, move method BEFORE parent::tearDown, it will work:
public function tearDown(): void
{
echo app()->environment();
parent::tearDown();
}
For posterity, my problem was something else entirely... I was trying to use config or env values in my unit test's "tearDown" method after calling the parent's implementation, which destroyed the application!
So this obviously does not work:
protected function tearDown(): void {
parent::tearDown();
$environment = App::environment();
...
}
but this will...
protected function tearDown(): void {
$environment = App::environment();
...
parent::tearDown();
}

PHP Fatal error: Class 'SoapClient' not found in laravel 5.4

I am working with laravel 5.4. The controller function that using laravel run in browser is working. Same function I called via scheduler it returns error.
Note: Soapclient is enabled in my server.
In Controller code:
use SoapClient;
$client = new SoapClient($wsdl, array(
'soap_version' => SOAP_1_1,
'trace' => true, //to debug
));
and in kernel.php
$schedule->command('eld:fetch')
->everyMinute();
PHP Fatal error: Class 'SoapClient' not found in laravel 5.4 means that the SoapClient class does not been enabled in your server. To do so, follow these steps:
Check first if it's enabled with phpinfo() function and look in the array if SoapClient is mentioned enabled. If it's not enabled, follow the second step.
Uncomment the extension=php_soap.dll line by removing the semicolon at the beginning, in php.ini file.
The next step is to restart your server.
Now return again to the first step to see if SoapClient is now enabled.
At this step, you can now import your class like this:
use SoapClient;
$client = new SoapClient($wsdl, array('soap_version' => SOAP_1_1, 'trace' => true));

JWTGenerateCommand::handle() does not exist

I am using Laravel 5.4 and JWT Auth Library for user authentication in API development. After installation while i am running php artisan jwt:generate then it throws me error of
Method Tymon\JWTAuth\Commands\JWTGenerateCommand::handle() does not exist
Any idea what i am missing ?
This error generally display when you install jwt package in laravel 5.5 version. then after you set service providers and run following command.
php artisan jwt:generate
then you seen this error message in terminal.
how to resolve it? simple follow this step
Step - 1 Re-install package
composer require tymon/jwt-auth:dev-develop --prefer-source
or the following is a new release package use laravel 6.X
composer require tymon/jwt-auth:1.0.*
in this developement version this errors fixed.
Step - 2 Set Service Provider
'providers' => [
....
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class to
Tymon\JWTAuth\Providers\LaravelServiceProvider::class
],
Step - 3 Generate key
php artisan jwt:secret
i found this solution from here https://laravelcode.com/post/method-tymonjwtauthcommandsjwtgeneratecommandhandle-does-not-exist
Go to JWTGenerateCommand.php file located in vendor/tymon/src/Commands and paste this method
public function handle() { $this->fire(); }
It's never a great idea to change anything in the vendor folder but the there's two ways to deal with this ...
Generate a random string yourself and just change the value in the JWT config file.
Go to Tymon\JWTAuth\Commands\JWTGenerateCommand and change the fire method to handle.
go to given file path
vendor/tymon/jwt-auth/src/Commands/JWTGenerateCommand.php
change function name
public function fire() to public function handle()
run command:
php artisan jwt:generate
I'm publishing this answer because I have crash in this error more than one time.
The only solution I found that it works with Laravel 5.6 is the following:
Add "tymon/jwt-auth": "1.0.0-rc.1" to composer.json and run composer update
Open config/app.php and add the following:
config/app.php:
'providers' => [
/*
* JWT Service Provider...
*/
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],
'aliases' => [
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
],
Execute:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
Finally, execute: php artisan jwt:secret
After all that, when I hit my endpoint for login I got the following exception:
Class Tymon\JWTAuth\Providers\JWT\NamshiAdapter does not exist
This was fixed by:
Open config/jwt.php and change the following:
config/jwt.php:
'jwt' => Tymon\JWTAuth\Providers\JWT\Namshi::class,
'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,
'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
Finally, note that in order to work your User model should be defined as follows:
class User extends Authenticatable implements JWTSubject
{
...
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
...
}
I can advise one solution. Go to JWTGenerateCommand.php file located in vendor/tymon/src/Commands and paste this part of code public function handle() { $this->fire(); }
I know this is not an elegant solution, but it works. I hope this might help until official fix arrive.
see here for more info
Change fire() function to handle() in this path
vendor/tymon/jwt-auth/src/commands/JWTGenerateCommand.php
In the file path: /vendor/tymon/jwt-auth/src/Commands/JWTGenerateCommand.php
Add public function
public function handle()
{
$this->fire();
}

Resources