Testing laravel api with jwt - laravel

I'm trying to write some test , the first test its for login route, I'm using jwt and mongodb, I set .env.testing identical to .env
DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=mydb
DB_USERNAME=myuser
DB_PASSWORD=mypass
this is phpunit.xml
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>
<server name="MAIL_DRIVER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
</php>
I tried with <server name="DB_CONNECTION" value="mongodb/> but I get the same error
and this is the test
<?php
namespace Tests\Unit;
use Tests\TestCase;
class AuthTest extends TestCase
{
/**
* A basic unit test example.
*
* #return void
*/
public function test_if_login()
{
$response = $this->json('POST', 'http://127.0.0.1:8000/auth', [
'email' => 'usuario1',
'password' => '12345'
]);
$response
->assertStatus(200)
->assertJsonStructure([
'data'=>[
'token'
]
]);
}
}
but I get this error
There was 1 failure:
1) Tests\Unit\AuthTest::test_if_login
Expected status code 200 but received 500.
Failed asserting that false is true.
Not sure about what is the problem

Related

I got “There is no active transaction” error after I added RefreshDatabase into test file

Making in laravel 9.48.0 with mysql database http tests after I added RefreshDatabase into test file
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling;
use Tests\TestCase;
use App\Models\{Article, User};
use Illuminate\Support\Str;
class ArticlesCrudTest extends TestCase
{
use InteractsWithExceptionHandling;
use RefreshDatabase;
I got “There is no active transaction” error on 1st test from 15 tests in this file
I do not use sqllite, but other mysql database, so phpunit.xml have sqlite and memory options disabled:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
printerClass="Sempro\PHPUnitPrettyPrinter\PrettyPrinterForPhpUnit9"
>
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./app</directory>
</include>
</coverage>
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/>
<!-- <env name="DB_CONNECTION" value="sqlite"/> -->
<!-- <env name="DB_DATABASE" value=":memory:"/> -->
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>
My control have code :
\Log::info( ' -1 store::');
DB::beginTransaction();
try {
$article = Article::create([
'title' => $data['title'],
'text' => $data['text'],
'text_shortly' => $data['text_shortly'],
'creator_id' => $data['creator_id'],
'published' => $data['published'],
]);
\Log::info( ' -2 store::');
DB::Commit();
$article->load('creator');
return response()->json(
['article' => (new ArticleResource($article))],
HTTP_RESPONSE_OK_RESOURCE_CREATED
); // 201
} catch (\Exception $e) {
DB::rollback();
}
In log file there are 2 lines from this controller. Before I added RefreshDatabase these tests worked ok, just like in real work.
What is wrong ?
Thanks!

Laravel DatabaseMigration not running migrations

I'm trying to create a very simple test, where it calls a service function that executes an ::all function in a model.
EDIT: As mentioned in a comment, I put it as a feature test, but still same issue:
namespace Tests\Feature;
use App\Models\FlashCard;
use App\Services\FlashCardService;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
use DatabaseMigrations;
/**
* A basic test example.
*
* #return void
*/
public function test_the_application_returns_a_successful_response()
{
$flashCardService = new FlashCardService();
$flashCardService::getAll();
}
}
The getAll() function all it does is:
public static function getAll(): Collection {
return FlashCard::all(['id', 'question', 'answer', 'status']);
}
The problem is that I get an error that the is no such table
General error: 1 no such table: flash_cards so the DatabaseMigrations is not running.
My phpunit.xml looks like this
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./app</directory>
</include>
</coverage>
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>
Any ideas?

Got "Access denied for user" when set database memory in laravel test

I'm trying to implement testing for my laravel project.
This is my phpunit.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./app</directory>
</include>
</coverage>
<php>
<server name="APP_ENV" value="testing"/>
<server name="APP_KEY" value="base64:in7fPzfWpFUCvr48DCZvkNf5qzqI/6SqSLpJysihepE=" />
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="DB_CONNECTION" value="mysql"/>
<server name="DB_DATABASE" value=":memory:"/>
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>
And I want to test database connect first, I've used RefreshDatabase trait to AutoRedirectTest (auto created when I creating project)
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Log;
use Tests\TestCase;
class AutoRedirectTest extends TestCase
{
use RefreshDatabase;
/**
* A basic test example.
*
* #return void
*/
public function test_home_redirect()
{
$response = $this->get('/');
$response->assertStatus(301);
$response->assertHeader('Location', '/nova');
}
}
Then when I run php artisan test, it throw error when testing AutoRedirectTest
SQLSTATE[HY000] [1044] Access denied for user 'apartment_management'#'%' to database ':memory:' (SQL: select * from information_schema.tables where table_schema = :memory: and table_name = migrations and table_type = 'BASE TABLE')
I've also tried to create new test file and add RefreshDatabase. I got the same error. But when I replace :memory: to my real database name. I've not got error above anymore.
<server name="DB_DATABASE" value="my_real_database_name"/>
So did I config something wrong?
I'm using laravel 8.61.0 with mysql 5.7.22 configured in docker.

how to fix Error: Call to a member function connection() on null in Laravel 7.xx PHPunit?

I duplicated the .env file of laravel and named it into .env.testing
inside the .env.testing file I have
DB_CONNECTION=sqlite
DB_DATABASE="C:/wamp64/wwww/myApp/test.sqlite"
then in the phpunit.xml i have this
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value="C:/wamp64/www/myApp/test.sqlite"/>
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
</php>
is my settings correct ?
In my test class I have this code
namespace Tests\Unit;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use PHPUnit\Framework\TestCase;
class CodeTest extends TestCase
{
use DatabaseMigrations;
public function test_can_push_data() {
$this->assertTrue(true);
}
}
When I tried to run
./vendor/bin/phpunit
1) Tests\Unit\CodeTest::test_can_push_data
Error: Call to a member function connection() on null
Any Idea why?

While running laravel phpunit testcase , i'm getting an error "Call to a member function connection() on null" in Model.php line 1249

I'm running laravel phpunit testcase, getting error in DB connection. DB connected successfully. But,
"Call to a member function connection() on null" - Could not open to
database connection server. Please update the configuration settings.
I did all those things properly. Find below details:
"php" : ">=7.1.3",
"laravel/lumen-framework": "5.8.*",
"phpunit/phpunit" : "^7.0",
"phpunit/php-invoker" : "*",
"phpunit/dbunit" : "^4.0",
This would be a bit of a guess without seeing your phpunit.xml configuration but I suspect you need to specify a connection for testing.
If you check your php unit file you should have some values like below in your php property.
Setting the DB_CONNECTION to sqlite and DB_DATABASE to :memory: is a fast and light-weight way to configure your testing DB.
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="MAIL_DRIVER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
</php>
If you do have similar values in your phpunit.xml file then you will need to check your config/database.php file and ensure the connection matching your DB_CONNECTION has a sensible configuration.
The default values for sqlite should work fine and are as follows:
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
Hope this helps.

Resources