Laravel unit testing assert functions always failing - laravel

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;
}
}

Related

partially mocking a class without affecting the private properties in PHP

I have a class with a lot of methods in which I need to mock only one method due to some sql incompatibility between mysql and in-memory sqlite database.
class OrderService implements OrderServiceContract
{
protected $deliveryService;
public function __construct(Delivery $deliveryService) // DI injected object
{
...
$this->deliveryService = $deliveryService;
...
}
public function methodNeedstoBeMocked()
{
....some sql related code...
}
public function returnToWarehouse($orderId)
{
DB::transaction(function() use ($orderId) {
...
$this->deliveryService->someOtherMethod($orderId); // problematic external service call
...
});
}
}
Now in my test I partially mock this class according to this doc link, and I call the returnToWarehouse from test but then it says that
Error : Call to a member function returnToWarehouse() on null.
meaning that the property $deliveryService doesn't exist on mock.
My test Implementation is as follows.
/**
* #test
*/
public function an_order_can_be_returned_to_warehouse()
{
...
...
$this->partialMock(OrderService::class, function ($mock) {
$mock->shouldReceive('methodNeedstoBeMocked')->andReturn(collect([]));
});
$orderService = app(OrderService::class);
$orderService->markOrderReturnedToWarehouse($order->id); // here is the problem gets triggered.
...
//assertions
}
What might be going wrong here? and what are some ways to mitigate this? Appreciate your help in advance.
The issue here is that partial test doubles from Mockery do not call the original constructor. For more information, please read the documentation here.
Alternatively, you could consider mocking the "problematic" method a bit differently. For example, you could extract that logic to a repository (since you mention that it is dealing with the database layer) that can then be mocked during your test.
Usually, When I have to mock some third party services I set up a Mock Like this.
This way you can set up easily your DI services
<?php
if (app()->environment('testing')) {
$this->app->bind(Delivery::class, static function () {
$service = \Mockery::mock(Delivery::class);
$service->shouldReceive('someOtherMethod')->andReturn([]);
return $service;
});
}

Laravel unit testing automatic dependency injection not working?

With Laravel Framework 5.8.36 I'm trying to run a test that calls a controller where the __construct method uses DI, like this:
class SomeController extends Controller {
public function __construct(XYZRepository $xyz_repository)
{
$this->xyz_repository = $xyz_repository;
}
public function doThisOtherThing(Request $request, $id)
{
try {
return response()->json($this->xyz_repository->doTheRepoThing($id), 200);
} catch (Exception $exception) {
return response($exception->getMessage(), 500);
}
}
}
This works fine if I run the code through the browser or call it like an api call in postman, but when I call the doThisOtherThing method from my test I get the following error:
ArgumentCountError: Too few arguments to function App\Http\Controllers\SomeController::__construct(), 0 passed in /var/www/tests/Unit/Controllers/SomeControllerTest.php on line 28 and exactly 1 expected
This is telling me that DI isn't working for some reason when I run tests. Any ideas? Here's my test:
public function testXYZShouldDoTheThing()
{
$some_controller = new SomeController();
$some_controller->doThisOtherThing(...args...);
...asserts...
}
I've tried things like using the bind and make methods on app in the setUp method but no success:
public function setUp(): void
{
parent::setUp();
$this->app->make('App\Repositories\XYZRepository');
}
That's correct. The whole idea of a unit test is that you mock the dependant services so you can control their in/output consistently.
You can create a mock version of your XYZRepository and inject it into your controller.
$xyzRepositoryMock = $this->createMock(XYZRepository::class);
$some_controller = new SomeController($xyzRepositoryMock);
$some_controller->doThisOtherThing(...args...);
This is not how Laravels service container works, when using the new keyword it never gets resolved through the container so Laravel cannot inject the required classes, you would have to pass them yourself in order to make it work like this.
What you can do is let the controller be resolved through the service container:
public function testXYZShouldDoTheThing()
{
$controller = $this->app->make(SomeController::class);
// Or use the global resolve helper
$controller = resolve(SomeController::class);
$some_controller->doThisOtherThing(...args...);
...asserts...
}
From the docs :
You may use the make method to resolve a class instance out of the
container. The make method accepts the name of the class or interface
you wish to resolve:
$api = $this->app->make('HelpSpot\API');
If you are in a location of your code that does not have access to the
$app variable, you may use the global resolve helper:
$api = resolve('HelpSpot\API');
PS:
I am not really a fan of testing controllers like you are trying to do here, I would rather create a feature test and test the route and verify everything works as expected.
Feature tests may test a larger portion of your code, including how
several objects interact with each other or even a full HTTP request
to a JSON endpoint.
something like this:
use Illuminate\Http\Response;
public function testXYZShouldDoTheThing()
{
$this->get('your/route')
->assertStatus(Response::HTTP_OK);
// assert response content is correct (assertJson etc.)
}

How to swap out dependency in laravel container

I have registered a Paypal service provider:
App\Providers\PaypalHelperServiceProvider::class,
and, when I type hint it in my controller it properly resolves:
public function refund(Request $request, PaypalHelper $paypal) {...
Here is my provider class:
class PaypalHelperServiceProvider extends ServiceProvider
{
protected $defer = true;
public function register()
{
$this->app->bind('App\Helpers\PaypalHelper', function() {
$test = 'test';
return new PaypalHelper();
});
}
public function provides()
{
$test = 'test';
return [App\Helpers\PaypalHelper::class];
}
}
Everything works as expected. Now I wanted to be able to modify controller to take a PayPal interface. I would then update my service provider to conditionally pass in either the real class or a mock one for testing, using the APP_ENV variable to determine which one to use. I put some debuggers into the service provider class and could not get it to ever go in. I thought perhaps that it only loads them on need, so I put a breakpoint inside my controller. The class did resolve, but it still never went into the service provider class! Can someone explain to me why this is the case? Even when I modified the code to pass in a different class type it did not pick up.
EDIT:
Here is the code flow I see when I debug this:
ControllerDispatcher -> resolveClassMethodDependencies -> resolveMethodDependencies -> transformDependency. At this point we have the following laravel code in the RouteDependencyResolveerTrait:
protected function transformDependency(ReflectionParameter $parameter, $parameters, $originalParameters)
{
$class = $parameter->getClass();
// If the parameter has a type-hinted class, we will check to see if it is already in
// the list of parameters. If it is we will just skip it as it is probably a model
// binding and we do not want to mess with those; otherwise, we resolve it here.
if ($class && ! $this->alreadyInParameters($class->name, $parameters)) {
return $this->container->make($class->name);
}
}
Since getClass() always resolves to the interface name, when we call container->make(), it always fails with
Target [App\Helpers\PaypalHelperInterface] is not instantiable.
Change
$this->app->bind('App\Helpers\PaypalHelper', function() {
$test = 'test';
return new PaypalHelper();
});
To
if (app()->environment('testing')) {
$this->app->bind(
PaypalHelperInterface::class,
FakePaypalHelper::class
)
} else {
$this->app->bind(
PaypalHelperInterface::class,
PaypalHelper::class
);
}
I finally found out the issue. My problem was that my provider wasn't being picked up at all. Here was the solution
composer dumpautoload
php artisan cache:clear
https://laravel.io/forum/02-08-2015-laravel-5-service-provider-not-working

Can't get Laravel relationship to work

I dont know what I'm doing wrong today, I can't get a 1-N relationship to work in Laravel 4. I'm trying to describe soccer teams that have many players.
I have a "players.team_id" field. I double-checked the database, the datas are OK.
First model :
class Team extends Eloquent {
public function players() {
return $this->hasMany('Player');
}
}
Second model :
class Player extends Eloquent {
function team() {
return $this->belongsTo('Team');
}
}
In my controllers, I can use $player->team but $team->players always retunrs null.
If I try to var_dump $team->players() (I should see the relationship description), it returns an error :
Call to undefined method Illuminate\Database\Query\Builder::players()
This is what my controller looks like :
class HomeController extends BaseController {
public function showTeam($slug) {
$team = Team::where('slug','=',$slug)->first();
// this works fine
$player = Player::find(1);
var_dump($player->team);
// this works, too.
$players = Player::where('team_id','=',516)->get();
var_dump($players);
$team = Team::where('slug','=',$slug)->first();
var_dump($team->players); // returns null
var_dump($team->players()); // throws an error
return View::make('team')
->with('team', $team);
}
}
Any leads ? Thank you very much !
I found the bug thanks to Quasdunk comment.
composer dump-auto
told me that I had twice the "Team" class.
Warning: Ambiguous class resolution
I copy/pasted a model file and forgot to change the class name in it. The problem was solved after I renamed this class.

Laravel - setting up a test database

With my laravel application I have a bunch of migrations and db seed data.
In app/config/testing/database.php I have set a mysql database for testing.
I've populated the test database with migrate and db:seed commands, specifying the testing environment.
This works pretty well, but I want to call those commands each time I run phpunit. If it do it in the setUp then it takes so long as it's called on every single test.
I can also call it in the setUpBeforeClass which is better, but still longer if I am testing 10 classes.
Is there a way I can all it just once when I run phpunit ?
For now I have done this, in the tests/TestCase.php
class TestCase extends Illuminate\Foundation\Testing\TestCase {
public static $setupDatabase = true;
public function setUp()
{
parent::setUp();
if(self::$setupDatabase)
{
$this->setupDatabase();
}
}
public function setupDatabase()
{
Artisan::call('migrate');
Artisan::call('db:seed');
self::$setupDatabase = false;
}
....
which seems to work, but doesn't feel ideal, but means I can easily re-setup the db if I need to reset it for a test...

Resources