簡體   English   中英

PHPUnit測試ZF2在模型上失敗

[英]PHPUnit testing ZF2 fail on model

我正在嘗試對此代碼進行簡單的單元測試:

  class IndexController extends CommonController
{  
    public function indexAction()
    {
    $this->layout('layout/layouthome');
    $language = $this->getLanguage($this->params('language'));

    $sm = $this->getServiceLocator();
    $tests = $sm->get('Tests');
    $users = $sm->get('Users');

    $this->layout()->language = substr($language, 0, 2);
    $translations = $this->getTranslations($sm, $language);
    $this->layout()->getAllTranslationByLocale = $translations;

    $userSession = $this->loginService->getSessionUser();

    if (!empty($userSession)) {
        $this->redirectUser($userSession, $language);
    }

    return new ViewModel(array(
        'translations' => $translations,
        'language' => $language,
        'getAllJobsByTopjobs' => $tests->getAllTestsByTopTests(),
        'countAllUsers' => $users->countAllUsers(),
    ));
    }
}

我的簡單測試是這樣的:

<?php namespace ApplicationTest\Controller;

use Zend\Stdlib\ArrayUtils;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;

class LogoutTest extends AbstractHttpControllerTestCase
{
    protected $traceError = true;

    public function setUp()
    {
        parent::setUp();
        $configOverrides = [];

        $this->setApplicationConfig(ArrayUtils::merge(
        // Grabbing the full application configuration:
            include __DIR__ . '/../../../../../config/application.config.php',
            $configOverrides
        ));

    }

    public function testIndexActionCanBeAccessed()
    {
        $this->dispatch('/');
        $this->assertResponseStatusCode(200);
    }
}

我遇到的問題是我無法實例化“測試和用戶”模型。 我是ZF2和單元測試的新手,因此非常感謝您的幫助。 謝謝

后期編輯

在setup()測試中添加

Bootstrap::getServiceManager();
$this->setApplicationConfig(Bootstrap::getConfig());

因此,現在所有配置都可以正確加載。 謝謝安德魯的所有幫助:)

我需要查看更多測試代碼,但是如果您使用的是基於zend的phpunit類,則需要設置配置,例如以下示例:

namespace Something;

use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;

class SomethingTest extends AbstractHttpControllerTestCase
{ 
    public function setUp()
    {
        // now the tests know how to load your config and
        // services / service manager etc.
        // this may be your main config or a test specific config
        $this->setApplicationConfig(
           include __DIR__ . '/../../config/application.config.test.php'
        );
    }

    public function testIndexActionCanBeAccessed()
    {
        // access via application object..
        $bla = $this->getApplication()->getServiceManager()->get('Tests');

        $this->dispatch('/');
        $this->assertResponseStatusCode(200);
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM