Setup VisualPHPUnit with Laravel - laravel

I'm using VisualPHPUnit as a GUI for my unit tests and I want to add it to my Laravel project.
I read this guide but it's obsolete being from 2015. There's no bootstrap.php file in config directory and there are no test_directories and bootstraps variables (I ran grep -rn . -e test_directories is Laravel directory).
Any idea what I can do to be able to add tests with artisan so they are working in VPU? Because Laravel test needs to extend Illuminate\Foundation\Testing\TestCase and VPU test needs to extend \PHPUnit_Framework_TestCase and I can't get it running. Either I don't see the test in VPU when I use Laravel's extend or I can't use Laravel's functions like visit when I use VPU's extend.
Edit:
Here's my PermissionTest.php:
<?php
namespace Visualphpunit\Test;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PermissionTest extends \PHPUnit_Framework_TestCase
{
protected $baseUrl = 'http://localhost/laravel/public';
public function testExample()
{
$this->visit('/')->see('Logowanie');
}
public function createApplication()
{
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
return $app;
}
}
...for which I get this error: Fatal error: Class 'Visualphpunit\Test\Illuminate\Foundation\Testing\TestCase not found in .../laravel/VisualPHPUnit-master/tests/PermissionTest.php on line 10

Related

How to extend a laravel package within laravel 5.8 application?

I am new to Laravel and would appreciate any help on describing how a Laravel package residing in vendor folder can be extended and wont get affected if I update the package.
I'll try to create a brief guide, and we'll expand if need be.
I suggest putting all of your files inside a separate directory / namespace. You'll benefit from this should you decide to create your own composer package afterwards.
As an example I'll extend bumbummen99/shoppingcart package which forks the great gloudemans/shoppingcart, adding support for Laravel 5.8 and some minor functionality. You will of course first need to install that package:
composer require bumbummen99/shoppingcart
Start by making a couple of folders. You can use any name for folders / classes, this is what I used, relative to the project root:
app/Repositories/ExtendedCart
app/Repositories/ExtendedCart/Facades
Create the file
app/Repositories/ExtendedCart/ExtendedCart.php
This class will extend the package's main class:
namespace App\Repositories\ExtendedCart;
use Gloudemans\Shoppingcart\Cart;
class ExtendedCart extends Cart
{
public function myMethod(){
return 'myMethod';
}
}
Then make your Service Provider. Create the file:
app/Repositories/ExtendedCart/ExtendedCartServiceProvider.php
(I'm not using artisan as generating / moving the provider will produce wrong namespace)
This is your Service Provider content, here you reference the class that extends the package's class. Note you overwrite the binding from the original package.
namespace App\Repositories\ExtendedCart;
use Gloudemans\Shoppingcart\ShoppingcartServiceProvider;
class ExtendedCartServiceProvider extends ShoppingcartServiceProvider
{
public function register()
{
$this->app->bind('cart', 'App\Repositories\ExtendedCart\ExtendedCart');
}
}
Then register your service provider in config/app.php
'providers' => [
...
//Add this line to the end of providers array
App\Repositories\ExtendedCart\ExtendedCartServiceProvider::class,
]
Lastly create a Facade, which will instantiate the class (otherwise you will get non-static method exceptions). Create this file:
app/Repositories/ExtendedCart/Facades/ExtendedCart.php
This is the contents of the file:
namespace App\Repositories\ExtendedCart\Facades;
use Illuminate\Support\Facades\Facade;
class ExtendedCart extends Facade {
protected static function getFacadeAccessor() { return 'cart'; }
}
You're all set to use your extended methods. You can safely upgrade the original package, and you can even use the default facade:
namespace App\Http\Controllers;
use Cart;
class SomeController extends Controller{
public function someFunction(){
Cart::instance('default')->myMethod();
//This should return 'myMethod'
}
}
I hope this helps, good luck!

Creating a helper system in laravel is correct or not?

My helper root
app\http\myHelpers\customClass.php
customClass.php
<?php
namespace App\Http\myHelper;
class CustomClass {
public static function customFunction(){
return 'Custom class working......';
}
}
Controller function
public function test(){
CustomClass::customFunction();
}
routes
Route::get('/test', 'HomeController#test');
There is no need composer command. It is work properly but I am not sure to is it correct system or wrong system. Please help me.
How you organize your code is honestly a personal choice. So there is nothing wrong with your code. You don’t need any composer command because in Laravel everything in the app folder is auto loaded by composer: The App Directory
This is perfectly fine, what you can do additionally is to organize function inside traits and place them e.g. in the /app folder.
<?php
namespace App;
trait HasRoles
{
public function hasPermission(Permission $permission)
{
return $this->hasRole($permission->roles);
}
}
and use this trait inside your controller like
use Authenticatable, Authorizable, CanResetPassword, HasRoles;
just another way of bundling helper functions!

Laravel 5 preventing 'use'

Is there a way to prevent using 'use' for everything. In Laravel 4 I never used 'use' and everything just worked. I'm now finding out I have to include everything, even 'DB' use DB. This is extremely frustrating and time consuming looking all this up.
My question is, is there an easier way to include everything?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Customer;
use DB;
class HomeController extends Controller {
}
?>
Thanks
Not really -- this is the Brave New Namespaced world of PHP 5.3+. Your class file above lives in the App\Http\Controllers namespace, which means when you type something like
$object = new SomeClass;
PHP will assume you mean the class App\Http\Controllers\SomeClass.
You'll either, as you complained about, need to use use, or you'll need to use the full classname (with a leading \ to let PHP know to start from the global namespace) whenever you want to use a class
class HomeController extends Controller {
public function someFunction()
{
$result = \DB::query(...);
$customer = new \App\Models\Customer;
//etc...
}
}
This is question is old but I found you can do this based on information from a tutorial by Tejas Jasani: http://www.theappguruz.com/blog/upgrading-from-laravel-4-2-to-5-in-web
Here are the key steps:
1 - Add the app/Http/Controllers directory to the "autoload" classmap directive of your composer.json file.
"autoload": {
"classmap": [
"database",
"app/Http/Controllers"
],
2 - Remove the namespace from the abstract app/Http/Controllers/Controller.php base class.
3 - In app/Providers/RouteServiceProvider.php file, set the namespace property to null
protected $namespace = null;
4 - Run "composer dump-autoload" from the command line.

Laravel 4 model unit test with Codeception - Class 'Eloquent' not found

I'm trying to use Codeception to run my Laravel 4 unit tests.
Running a test for a simple class with no dependencies works fine. But when I instantiate a model which depends on Eloquent, I get this fatal error:
PHP Fatal error: Class 'Eloquent' not found in /var/www/project/app/models/Role.php on line 4
Unit test:
<?php
use Codeception\Util\Stub;
class TestModel extends \Codeception\TestCase\Test
{
public function testExample()
{
$role = new Role;
$role->name = 'superuser';
$this->assertEquals('superuser', $role->name);
}
}
Model:
<?php
class Role extends Eloquent
{
public function users()
{
return $this->belongsToMany('User');
}
}
Project structure:
I'm running vendor/bin/codecept run unit from the project root, with this file structure:
/project
codeception.yml
/vendor/bin/codecept
/app
/tests
unit.suite.yml
/unit
ExampleTest.php
/models
Role.php
...etc
What am I doing wrong?
By looking at the Codeception L4 sample app, I was able to see how to bootstrap the autoload to resolve this issue, by adding these lines to project/app/tests/_boostrap.php:
include __DIR__.'/../../vendor/autoload.php';
$app = require_once __DIR__.'/../../bootstrap/start.php';
\Codeception\Util\Autoload::registerSuffix('Page', __DIR__.DIRECTORY_SEPARATOR.'_pages');
Edit: when upgrading from Laravel 4.0 to 4.1, it is also necessary to add an extra line:
$app->boot();
I'm probably late to the party, but if you don't need the codecept stuff. You should be extending laravel's implementation of PHPUnit_Framework_TestCase called just TestCase. Like this:
class TestModel extends TestCase {
}
The answer to this question is a little outdated now. With Laravel 5 I got the same error (Class 'Eloquent' not found...) and solved it by copying the code from Laravels base TestCase.php file. This file is used for testing within the Laravel framework (NOT using codeception).
To fix the 'Eloquent not found' error, add the following lines to project/tests/unit/_bootstrap.php
<?php
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
Honestly I'm not sure why it works, but it does! I'll edit if I figure out why or someone comments.
The Eloquent class cannot be found when you are running your unit tests.
Try adding use Illuminate\Database\Eloquent\Model as Eloquent; to Role.php.
You can go to TestCase class and override method refreshApplication (add method to TestCase) with adding auth or some:
protected function refreshApplication()
{
$this->app = $this->createApplication();
$this->client = $this->createClient();
$this->app->setRequestForConsoleEnvironment();
$this->app->boot();
// authenticate your user here, when app is ready
$user = new User(array('username' => 'John', 'password' => 'test'));
$this->be($user);
}
I solved a similar problem with Laravel 4 and Codeception by adding the following lines to _bootstrap.php
$app = require __DIR__.'/../../bootstrap/start.php';
$app->boot();
Hope this helps a fellow googler!

Laravel 4 Aliases in custom classes

i want to use the alias classes on laravel 4 "facades" like App::method , Config::method.
Well the thing is that i create a custom class and i have to import the namespaces like
<?php
namespace Face\SocialHandlers;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
class FacebookHandler implements SocialHandlerInterface {
public function registrar($perfil) {
Config::get('facebook');
}
}
is there any way to use those classes like in controllers or routes files of the framework ?
like
<?php
namespace Face\SocialHandlers;
//use Illuminate\Support\Facades\App;
//use Illuminate\Support\Facades\Config;
class FacebookHandler implements SocialHandlerInterface {
public function registrar($perfil) {
Config::get('facebook');
}
}
Cya
ps: sry for my english
You can use use Config; instead of the more verbose use Illuminate\Support\Facades\Config; and the autoloader should handle it correctly.
Just as a tip, you shouldn't hardcode dependencies in your code. Instead of using the facades, you could create an "ConfigInterface" to get the common dependencies you need. Then create a "LaravelConfig class" (Or Laravel4Config.php) and implement those methods.
For a Quick Fix Answer, "catch the underliying facade instance":
namespace Face\SocialHandlers;
//use Illuminate\Support\Facades\App;
//use Illuminate\Support\Facades\Config;
class FacebookHandler implements SocialHandlerInterface {
protected $config;
protected $app;
public function __construct()
{
$this->config = \Illuminate\Support\Facades\Config::getFacadeRoot();
$this->app = \Illuminate\Support\Facades\App::getFacadeRoot();
}
public function registrar($perfil) {
$this->config->get('facebook');
}
}
For a Real Answer, maybe tedious, but good in the long run, instead of using the facades use an interface.
interface SocialConfigInterface
{
public function getConfigurationByKey($key)
}
Then
class Laravel4Config implements SocialConfigInterface
{
protected $config;
public function __construct()
{
$this->config = \Illuminate\Support\Facades\Config::getFacadeRoot(); //<-- hard coded, but as expected since it's a class to be used with Laravel 4
}
public function getConfigurationByKey($key)
{
return $this->config->get($key);
}
}
And Your Code
namespace Face\SocialHandlers;
//use Illuminate\Support\Facades\App;
//use Illuminate\Support\Facades\Config;
class FacebookHandler implements SocialHandlerInterface {
protected $config;
public function __construct(SocialConfigInterface $config)
{
$this->config = $config;
}
public function registrar($perfil) {
$this->config->get('facebook');
}
}
This way, if you want to change between frameworks you just need to create a SocialConfigInterface Implementation, or imagine the scenario where Laravel 5 wont use Facades, you want your code to be independent of "outsider changes" this is inversion of control IoC
First run,
php artisan dump-autoload
This will add your class namespace to vendor/composer/autoload_classmap.php. Now locate the entry for your class in this classmap array and get the proper namespace from there.
For example, you will get something like,
'Illuminate\\Support\\Facades\\App' => $vendorDir . '/laravel/framework/src/Illuminate/Support/Facades/App.php',
For this particular entry you have an alias in app/config/app.php
'App' => 'Illuminate\Support\Facades\App',
At the same way, locate your entry and use an alias in app/config/app.php.
You just have to create a folder, or place a class wherever already is listed for autoload. Me, for exemple, have this class PDFMaker, that uses a DomPDF Laravel implementation. I created a folder named libraries and put the path to it (under the app folder) in the autoload:classmap key on composer.json
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/libraries",
"app/models",
"app/helpers",
"app/database/migrations"
]
I did the same with commands for artisan commands! When you do that, you only have to declare a new object for any class under that folder, or call it in a static way, if the class has defined static methods. Something like Class::method.
Hope it helps you, have a nice day! :D
EDIT: After that, don't forget the dump-autoload for placing the new class in autoload scope.
EDIT 2: Remember that once you've put the class on autoload, it will be in same scope the others, so you won't have to import it to other, neither others to it!
You can also prefix the class names with a backslash, to use the global namespace: \Config::get('facebook') and \App::someMethod() will work without the need to add a use statement, regardless of the file's namespace.

Resources