Laravel测试if / else语句 - 单元测试

时间:2016-04-22 12:56:04

标签: php unit-testing if-statement laravel-5 mockery

有人可以帮助我在控制器中测试功能吗?无法测试控制器中的if语句,所以请关注这段代码。 对此控制器的其他测试很好,但只能测试“if语句”中的代码。

LanguageController.php

class LanguageController extends Controller implements IEntityViewManager
{
    protected $languageRepo;

    public function __construct(LanguageRepositoryInterface $languageRepo)
    {
        $this->languageRepo = $languageRepo;
    }

    public function createAction(LanguagePostRequest $request)
    {
        $languages = $this->languageRepo->whereCharOrName($request->char, $request->name);

        if(count($languages) > 0)
        {
            return redirect()->back()->withErrors("Already exists")->withInput();
        }

        $language = new Language();
        $this->languageRepo->store($language, $request->all());

        return redirect()->route('Admin.Language.showAllView');
    }
}

以下是此测试的测试要求:

LanguageControllerTest.php

class LanguageControllerTest extends TestCase
{
    public function __construct($name = NULL, array $data = array(), $dataName = '')
    {
        parent::__construct($name, $data, $dataName);
    }

    public function setUp()
    {
        parent::setUp();
    }

    public function tearDown()
    {
        Mockery::close();
    }

    protected function setUpMock()
    {
        $mock = Mockery::mock(LanguageRepositoryInterface::class);
        $this->app->instance(LanguageRepositoryInterface::class, $mock);

        return $mock;
    }

    public function testInvalidInsertLanguage1()
    {
        $params = array(
            'char' => 'en',
            'name' => 'English'
        );

        $mock = $this->setUpMock();

        // HELP ME TO TEST IF STATEMENT AND TO REDIRECT BACK WITH ERRORS AND INPUTS
        // NEED CONTENT

        $this->action('POST', 'Entities\LanguageController@createAction', null, $params);
    }

或许我应该避免使用if语句并将其放在控制器中的其他函数中,但是测试起来太复杂了,因为我应该模拟这个控制器?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作,这将设置一个模拟器,该模拟器需要初始化语言的方法。现在,因为您只想测试count方法,所以只返回一个包含元素的数组。这将测试控制器的重定向部分。我还没有运行这段代码,但希望你能得到这个想法。

public function setUp()
{
    $this->mock = Mockery::mock("LanguageRepositoryInterface");
}

public function testInvalidInsertLanguageRedirect()
{
    $params = array(
        'char' => 'en',
        'name' => 'English'
    );

    $this->mock
         ->shouldReceive("whereCharOrName")
         ->once()
         ->andReturn([1]);

    $response = $this->action('POST', 'Entities\LanguageController@createAction', null, $params);
    $this->assertEquals(301, $response->status());   
}