1

How can i test my function which has __construct ?

For ex my controller code looks like :

    namespace App\Http\Controllers; 
    use App\Repositories\UserAccountRepository;
    class UserController extends ProtectedController
    {
      protected $userAccountRepository;
      public function __construct(userAccountRepository 
      $userAccountRepository){
        parent::__construct();
        $this->userAccountRepository = $userAccountRepository;
    }

    public function FunctionWantToTest(){
        return 'string';
    }

The unit test required to fulfill the construct first before test my FunctionWantToTest.

So, my test code looks like,

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Http\Controllers\UserController;

class UserTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testUserList()
    {

        $UserController = new UserController(???what value??);
        $this->assertTrue(true);
    }
}

Need more help (best practice) how to test the code which has construct.

Bobby
  • 253
  • 1
  • 4
  • 20

2 Answers2

1

I think you just need to use app->make:

class UserTest extends TestCase
{

    protected $userController;

    public function setUp() {

        parent::setUp();

        $this->userController = $this->app->make(UserController::class);
    }

    /**
     * A basic test example.
     *
     * @return void
     */
    public function testUserList()
    {
        $this->userController // do what you need here...
        $this->assertTrue(true);
    }
}
Alex Harris
  • 6,172
  • 2
  • 32
  • 57
  • Would you tell me, 1. what for is setUp() ? is this default ? 2. what is this ? $this->app->make(UserController::class); 3. what can i do here? $this->userController // do what you need here... – Bobby Sep 28 '17 at 04:25
0

Use feature test or integration test when test controller,

You can see this brief explanation about unit test and integration test.

What's the difference between unit tests and integration tests?

rslhdyt
  • 149
  • 2
  • 14