How to Run Laravel Database Seeder from PHPUnit Test setUp? - laravel

I am trying to recreate the database before each test in some PHPUnit test cases. I am using Laravel 5.3. Here is TestCase:
class CourseTypesTest extends TestCase
{
public function setUp()
{
parent::setUp();
Artisan::call('migrate');
Artisan::call('db:seed', ['--class' => 'TestDatabaseSeeder ', '--database' => 'testing']);
}
/**
* A basic functional test example.
*
* #return void
*/
public function test_list_course_types()
{
$httpRequest = $this->json('GET', '/api/course-types');
$httpRequest->assertResponseOk();
$httpRequest->seeJson();
}
public function tearDown()
{
Artisan::call('migrate:reset');
parent::tearDown();
}
}
Running phpunit fails with error:
$ phpunit PHPUnit 5.7.5 by Sebastian Bergmann and contributors.
E 1 /
1 (100%)
Time: 2.19 seconds, Memory: 12.00MB
There was 1 error:
1) CourseTypesTest::test_list_course_types ReflectionException: Class
TestDatabaseSeeder does not exist
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Container\Container.php:749
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Container\Container.php:644
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:709
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Database\Console\Seeds\SeedCommand.php:74
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Database\Console\Seeds\SeedCommand.php:63
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:2292
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Database\Console\Seeds\SeedCommand.php:64
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Container\Container.php:508
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Console\Command.php:169
D:\www\learn-laravel\my-folder-api\vendor\symfony\console\Command\Command.php:254
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Console\Command.php:155
D:\www\learn-laravel\my-folder-api\vendor\symfony\console\Application.php:821
D:\www\learn-laravel\my-folder-api\vendor\symfony\console\Application.php:187
D:\www\learn-laravel\my-folder-api\vendor\symfony\console\Application.php:118
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Console\Application.php:107
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:218
D:\www\learn-laravel\my-folder-api\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:237
D:\www\learn-laravel\my-folder-api\tests\rest\CourseTypesTest.php:17
ERRORS! Tests: 1, Assertions: 0, Errors: 1.
but this class exists:

Since version 5.8 you can do:
// Run the DatabaseSeeder...
$this->seed();
// Run a single seeder...
$this->seed(OrderStatusesTableSeeder::class);
Take a look at the documentation

The DatabaseSeeder can be instantiated on its own, and its call method is public.
All you need to do in your CourseTypesTest class would be
(new DatabaseSeeder())->call(TestDatabaseSeeder::class);
Or you can make use of Laravel's app helper as follow
app(DatabaseSeeder::class)->call(TestDatabaseSeeder::class);

The problem is empty space in your --class argument. If you take close look at array '--class' => 'TestDatabaseSeeder ' there is space in the end ... this is the problem. Change it to '--class' => 'TestDatabaseSeeder' and it should work fine.

You can try this way. You can execute this command when you run your test.

Related

PHPUnit show errors but not show successful alert

I use Laravel 5.8 and phphunit version 7.5. When I run PHPUnit with error, show me error but when not has error show me only this line
PHPUnit 7.5.0 by Sebastian Bergmann and contributors.
My test class:
use Tests\TestCase;
class leadTest extends TestCase
{
public $Array= ['lead_name' => 'Jon','lead_family'=>'Doe'];
public function test_store()
{
$this->withoutExceptionHandling();
$this->post('leads', $this->Array());
$this->assertDatabaseHas('leads', $this->Array);
}
}
That is the reason of your error:
$this->withoutExceptionHandling();
Try without it.
Look also at class name it should be: LeadTest, and the file should be named LeadTest.php

Why would the example test in Laravel fail for redirect?

Please explain why Laravel 4's example test fails for me.
My "/" route redirects to "login" in my routes.php file.
(Oh, I've RTFMed and scoured several sites, blogs, and tuts.)
-sh-3.2$ phpunit
PHPUnit 4.0.7 by Sebastian Bergmann.
Configuration read from /home/dev/phpunit.xml
The Xdebug extension is not loaded. No code coverage will be generated.
F
Time: 83 ms, Memory: 13.50Mb
There was 1 failure:
1) ExampleTest::testBasicExample
Failed asserting that false is true.
/home/dev/app/tests/ExampleTest.php:14
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
-sh-3.2$
Here is the code from ExampleTest.php
<?php
class ExampleTest extends TestCase {
/**
* A basic functional test example.
*
* #return void
*/
public function testBasicExample()
{
$crawler = $this->client->request('GET', '/');
$this->assertTrue($this->client->getResponse()->isOk());
}
}
The test is failing because you're getting 302 status code instead of 200 (since there is a redirection that wasn't in the default routes.php file).
If you want to test redirection, then Laravel provides several methods just for that.
If you're using named routes:
$this->assertRedirectedToRoute('login');
If not:
$this->assertRedirectedTo('login');
For testing response status codes:
$this->assertResponseStatus(302);

Class 'Eloquent' not found when mocking in Laravel

I'm following through Jeffrey Way's Laravel Testing Decoded and I've hit an issue I can't seem to fix.
I'm actually work through this tutorial: http://net.tutsplus.com/tutorials/php/testing-laravel-controllers/ Which is an excerpt from his book.
Basically I have a test like so:
class PostsTest extends TestCase {
public function __construct()
{
$this->mock = Mockery::mock('Eloquent', 'Post');
}
And that like for mocking Eloquent and Post returns:
PHP Fatal error: Class 'Eloquent' not found
When I run phpunit. Incidentally if I use Jeffrey's Laravel Generators and just generate some scaffold e.g.
php artisan generate:scaffold post --fields="title:string, body:string"
And run phpunit I get same error. He's using the same:
$this->mock = Mockery::mock('Eloquent', 'Post');
To mock the classes. Does anyone have any suggestions on what the issue could be?
I've been working through the tutorial again from scratch and am still getting the same error. I've pushed it to a public repo so people can see: https://github.com/RyanHavoc/tdd-laravel
Just pull it down, run composer install/update and phpunit.
I found a solution to the issue.
//Causes the Class 'Eloquent' not found error
public function __construct()
{
$this->mock = Mockery::mock('Eloquent', 'Post');
}
//Setting the mocks in the setUp() method instead works
public function setUp()
{
parent::setUp();
$this->mock = Mockery::mock('Eloquent', 'Post');
}

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 unit testing on windows keeps giving error

I have a Laravel 4 installation right out of the box. I am running Windows 8 64 bit with PHP 5.5, Apache 2.2 through XAMPP.
When I run phpunit I get the standard laravel error page Whoops, looks like something went wrong. and right above it I see PHPUnit 3.8-dev by Sebastian Bergmann. Configuration read from C:\project\phpunit.xml The Xdebug extension is not loaded. No code coverage will be generated.
If I delete file app/tests/ExampleTest.php then phpunit seems to work and I get
PHPUnit 3.8-dev by Sebastian Bergmann.
Configuration read from C:\project\phpunit.xml
The Xdebug extension is not loaded. No code coverage will be generated.
Time: 232 ms, Memory: 2.75Mb
←[30;43mNo tests executed!←[0m
app/tests/ExampleTest.php
<?php
class ExampleTest extends TestCase {
/**
* A basic functional test example.
*
* #return void
*/
public function testBasicExample()
{
$crawler = $this->client->request('GET', '/');
$this->assertTrue($this->client->getResponse()->isOk());
}
}
app/tests/TestCase.php
<?php
class TestCase extends Illuminate\Foundation\Testing\TestCase {
/**
* Creates the application.
*
* #return Symfony\Component\HttpKernel\HttpKernelInterface
*/
public function createApplication()
{
$unitTesting = true;
$testEnvironment = 'testing';
return require __DIR__.'/../../bootstrap/start.php';
}
}

Resources