4

To start from the conclusion, I get this error:

[ErrorException]                                                                                                                                                                                    
Argument 1 passed to SomeValidatorTest::__construct() must be an instance of App\Services\Validators\SomeValidator, none given, called in ....vendor/phpunit/phpunit/src/Framework/TestSuite.php on line 475 and defined  

In Laravel app, I have a script called "SomeValidator.php" which looks like this:

<?php namespace App\Services\Validators;

use App\Services\SomeDependency;

class SomeValidator implements ValidatorInterface
{

    public function __construct(SomeDependency $someDependency)
    {
        $this->dependency = $someDependency;
    }

    public function someMethod($uid)
    {
       return $this->someOtherMethod($uid);
    }

}

which runs without error.

Then the test script, SomeValidatorTest.php looks like this:

<?php

use App\Services\Validators\SomeValidator;


class SomeValidatorTest extends TestCase
{
    public function __construct(SomeValidator $validator)
    {
        $this->validator = $validator;
    }

    public function testBasicExample()
    {
        $result = $this->validator->doSomething();
    }
}

The error shows up only when the test script is ran through './vendor/bin/phpunit' The test class seems to be initiated without the dependency stated and throws an error. Does anyone know how to fix this? Thanks in advance.

1 Answer 1

6

You cannot inject classes into the tests (as far as i know), given that they are not resolved automatically by laravel/phpUnit.

The correct way is to make (resolve) them through laravel's app facade. Your test script should look like this:

<?php

class SomeValidatorTest extends TestCase
{
    public function __construct()
    {
        $this->validator = \App::make('App\Services\Validators\SomeValidator');
    }

    public function testBasicExample()
    {
        $result = $this->validator->doSomething();
    }
}

Source: http://laravel.com/docs/5.1/container

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.