TestCase Laravel Custom Command returns empty response - laravel

I'm trying to test my custom command, but when I run it does not return anything. I do not know if it's a problem with my assertion. I'm using Laravel 5.6
class CommandsTest extends TestCase
{
//Command morty:bloquear_usuarios_demitidos
public function test_if_can_run_command_morty_bloquear_usuarios_demitidos()
{
$response = $this->artisan('morty:bloquear_usuarios_demitidos');
$response->assertContains('Executado');
}
}
phpunit test

I am not sure what you are expecting an artisan command to 'return'. They don't 'return' things, they just get executed. There could be an exit code, but that is it.
If you stop and look at the method you are calling artisan it returns an int. You can't expect anything other than an int which would be the exit code.
Laravel 5.6 API - InteractsWithConsole#artisan

Related

Laravel unit testing assert functions always failing

I have created a very basic unit testing class under Laravel root-->tests-->Unit-->SimpleTest.php
Inside the file i have import the controller class that i need to test. And test function is like this.
class SimpleTest extends TestCase
{
public function testLoadUsers()
{
$controller_obj = new UsersController;
$data_status = $controller_obj->load_users();
if($data_status != null){
$this->assertTrue(true);
}
else{
$this->assertTrue(false);
}
}
}
I executed this test case in Artisan console like this,
php vendor/phpunit/phpunit/phpunit tests/Unit/SimpleTest.php
Always this fails. My controller function returning data as well without an issue. I tested without defining any condition and just,
$this->assertTrue(true);
Then it works. So i assume there is no any issue with the phpunit test command as well.
I'm sorry, this is not a direct answer.
I think maybe you should check the value of $data_status by this.
class SimpleTest extends TestCase
{
public function testLoadUsers()
{
$controller_obj = new UsersController;
$data_status = $controller_obj->load_users();
$this->expectOutputString('Array');
print data_status;
}
}

How to mock only one method with Laravel using PhpUnit

I have this test :
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Services\AccessTokenService;
use App\Services\MemberService;
class BranchTest extends TestCase
public function testPostBranchWithoutErrors()
{
$this->mock(AccessTokenService::class, function ($mock) {
$mock->shouldReceive('introspectToken')->andReturn('introspection OK');
});
$this->mock(MemberService::class, function ($mock) {
$mock->shouldReceive('getMemberRolesFromLdap')->andReturn(self::MOCKED_ROLES);
});
As you see, there are 2 mocks on this test. The 2nd one 'MemberService:class' is my current problem. In this class there are 2 functions : 'createMember' and 'getMemberRolesFromLdap'. I precise that I want to mock only the 'getMemberRolesFromLdap' function.
In the documentation, it is written :
You may use the partialMock method when you only need to mock a few methods of an object. The methods that are not mocked will be executed normally when called:
$this->partialMock(Service::class, function ($mock) {
$mock->shouldReceive('process')->once();
});
But when I use "partialMock", I have this error:
Error: Call to undefined method Tests\Feature\BranchTest::partialMock()
And when I try a classic mock (no partial), I have this error:
Received Mockery_1_App_Services_MemberService::createMember(), but no expectations were specified
certainly because there are 2 functions in this class and so PhpUnit does not know what to do with the function 'createMember'.
What can I try next? I am a beginner to PhpUnit tests.
Edit
Laravel 6.0
PhpUnit 7.5
PartialMock shorthand is firstly added in Laravel 6.2 see the release notes. So an upgrade to 6.2 should fix your problem.
Secondly you can add the following snippet to your Tests\TestCase.php class and it should work.
protected function partialMock($abstract, Closure $mock = null)
{
return $this->instance($abstract, Mockery::mock(...array_filter(func_get_args()))->makePartial());
}

Laravel 5.4 using Mail fake with Mail::queue, Mail::assertSent not working

I am writing unit test for a code that sends email with Mail::queue function, like the one in the documentation: https://laravel.com/docs/5.4/mocking#mail-fake
My Test:
/** #test */
public function send_reminder()
{
Mail::fake();
$response = $this->actingAs($this->existing_account)->json('POST', '/timeline-send-reminder', []);
$response->assertStatus(302);
Mail::assertSent(ClientEmail::class, function ($mail) use ($approver) {
return $mail->approver->id === $approver->id;
});
}
Code being Tested:
Mail::to($email, $name)->queue(new ClientEmail(Auth::user()));
Error Message:
The expected [App\Mail\ClientEmail] mailable was not sent.
Failed asserting that false is true.
The email is sent when I manually test it, but not from Unit Test. I'm thinking it might be because I am using Mail::queue instead of Mail::send function.
In .env file, I have
QUEUE_DRIVER=sync and MAIL_DRIVER=log
How can I test Mail::queue for Laravel?
Found the solution:
The problem was that the class was not imported at the top of PHPUnit test file.
Importing the mail class solved the issue. Strange how it didn't error out the testcase itself.

Call to a member function connection() on null Laravel 5.4

Try write a unit test and i need do sql query
class UpdateThrowsTest extends TestCase
{
protected $bgame;
protected $game_id = 95;
public function setUp(){
$game = new Game();
$game = $game::find($this->game_id);
}
}
and then i write "phpunit" in console and try exception
Call to a member function connection() on null.
If anyone bounce to this error during test with Laravel 6 project.
Try to check if the extends TestCase is using the right TestCase.
It could be due to Laravel 6 make:test generated test using the wrong TestCase.
Change
use PHPUnit\Framework\TestCase;
To
use Tests\TestCase;
The problem should solve.
I had this error on laravel 7 (nothing worked even php artisan serve) and fixed it with
composer dumpautoload
Before that update my vendor with composer update and then everything worked fine.

How check if a Laravel Console Command Exists?

I need to check if a Laravel Console Command exists and if it is in the protected command var to call them.
I need to call them from another Laravel console command. And I want to know if there are something like exists_command('mycommand:foo')
There are any way to achieve this?
Tested and working.
function command_exists($name)
{
return array_has(\Artisan::all(), $name);
}
if (command_exists('config:cache')) {
// success
}
Though #Sandeesh is right, we can check in this way:
function exists_command($name)
{
return array_key_exists($name, \Artisan::all());
}
if (exists_command('mycommand:foo')) {
// success
}
even in a shorter way,
function exists_command($name)
{
return $this->getApplication()->has($name);
}
php artisan list
Will bring up all possible artisan commands. There is a 'command' subsection with your own created commands.
You would call them as follows
php artisan command:MyCreatedCommand
Edit: To check if a command exists in your project you can use php class_exists function
if(class_exists('App\Console\Commands\MyCommandName')){
//Do whatever
}

Resources