1
votes

I'm trying to unit test "AdminService" class that has "create()" method and in the constructor I need a dependency which is AdminRepository.

I used mockery to mock the repository and passed this mock to AdminService _contsruct() but i got and error when i run the test that says: Error: Call to a member function create() on null

This is the AdminService that I'm trying to test : I followed this article : Unit tests – complex argument matching with Mockery::on – the right way

use App\Repositories\AdminRepository;

class AdminService {

    protected $admin_repo;

    public function _contsruct(AdminRepository $admin_repo){
        $this->$admin_repo= $admin_repo;
    }

    public function create($data){
        return  $this->admin_repo->create($data); 

    }



}  

and the test code is :

/** @test */
   public function it_can_create_Admin(){

      $data=[
         "first_name"=>"lama",
         "last_name"=>"sonmez",
         "email"=>"[email protected]",
         "password"=>"secret"
      ];


      $repo_mock = Mockery::mock(AdminRepository::class);
      $repo_mock->shouldReceive('create')->once()->with($data)
          ->andReturn('anything');
      $admin_service = new AdminService($repo_mock);
      $admin = $admin_service->create($data);
      $this->assertInstanceOf(Admin::class,$admin);

   }   

I don't know what's wrong here , please help.

when I dd($repo_mock) is gives me the mock I mean it's not null
but when I dd($admin_service) I got

App\Services\AdminService^ {#4106
  #admin_repo: null
}  
1

1 Answers

-1
votes

Oh I figured out why this happens, this was because of the underscore sign for the constructors in AdminRepository and AdminService it should have two underscores before the construct keywork like this __construct and not like this _construct