本文介绍了Laravel 5-单元测试-状态码500,预期200的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么测试1"中的单元测试会向我返回状态代码500,而不是200?有人可以向我解释吗?这是2个测试中相同动作的示例,它们返回不同的状态代码.我在两个测试中都希望有200个?

Why unit test in "test 1" returns me status code 500, not 200 ? Can somebody explain me ?Here is example in 2 tests for same action and they return different status code. I expected 200 in both tests ?

LanguageController

    class LanguageController extends Controller implements IEntityViewManager
    {
          public function showAllView()
          {
              $allLanguages = $this->languageRepo->orderBy('id');

              return view('admin.languages.showAll')->with('languages', $allLanguages);
          }
    }

LanguageControllerTest

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

    // test 1
    public function testShowAllLanguages()
    {
        $mock = $this->setUpMock();

        $mock->shouldReceive('orderBy')->once()->andReturn([1]);

        $result = $this->action('GET', 'Entities\LanguageController@showAllView');

        var_dump("Test 1 : " . $result->getStatusCode()); // RETURNS 500
    }

    // test 2
    public function testShowAllView()
    {
        $result = $this->action('GET', 'Entities\LanguageController@showAllView');

        var_dump("Test 2 : " . $result->getStatusCode()); // RETURNS 200

        $this->assertViewHas('languages');

        $this->assertResponseOk();
    }
}

以cmd回应:

推荐答案

我检查了laravel.log,发现了下一个日志:

I checked laravel.log and I found next logs:

和下一个日志:

堆栈跟踪:

在我看来,我可以通过以下方式访问$ language属性:

and on my view i access to $language properties with :

$ languages-> char,$ language-> name

$languages->char, $language->name

但是它是数组,所以我应该使用:

but it is array so I should access with:

$ language ['char'],$ language ['name']

$language['char'], $language['name']

这两个测试现在都可以正常工作,并返回状态码200 .

and both tests now work properly and returns status code 200.

谢谢大家的帮助.

这篇关于Laravel 5-单元测试-状态码500,预期200的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:49