繁体   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