标签: phpunit

如何使用PHPUnit测试Factory/Strategy实现

我有一个Factory类,它根据给定文件的扩展名返回一个编写器策略:

public static function getWriterForFile($file)
{
    // create file info object
    $fileInfo = new \SplFileInfo($file);
    // check that an extension is present
    if ('' === $extension = $fileInfo->getExtension()) {
        throw new \RuntimeException(
            'No extension found in target file: ' . $file
        );
    }
    // build a class name using the file extension
    $className = 'MyNamespace\Writer\Strategy\\'
        . ucfirst(strtolower($extension))
        . 'Writer';
    // attempt to get an instance of the class
    if (!in_array($className, get_declared_classes())) {
        throw new \RuntimeException(
            'No writer could be found …
Run Code Online (Sandbox Code Playgroud)

php phpunit factory mocking strategy-pattern

0
推荐指数
1
解决办法
3893
查看次数

Selenium Web Driver:php-webdriver-bindings的findElementsBy()函数返回错误

我正在编写代码自动生成的下拉,如谷歌搜索帮助,并尝试打印自动生成的下拉值作为输出.

在selenium WebDriver中捕获多个与xpath定位符匹配的元素,我们必须使用findElementsBy()函数,

我写的代码如下

<?php 
require_once 'www/library/phpwebdriver/WebDriver.php';
class PHPWebDriverTest extends PHPUnit_Framework_TestCase {
 protected $webdriver;

    protected function setUp() {
        $this->webdriver = new WebDriver("localhost", 4444);
        $this->webdriver->connect("firefox");
    }

    protected function tearDown() {
    //    $this->webdriver->close();
    }
    public function testgooglesearch() {                          
    $this->webdriver->get("http://google.com");
    $element=$this->webdriver->findElementBy(LocatorStrategy::name, "q");           
    $element->sendKeys(array("selenium" ) );
    $result=$this->webdriver->findElementsBy(LocatorStrategy::xpath,"//*[@id=\'gsr\']/table/tbody/tr/td[2]/table/tbody/tr[*]/td/");
    echo $countresult=count($result);

    }
}
?>
Run Code Online (Sandbox Code Playgroud)

根据绑定,findElementsBy()函数将假设返回一个数组.所以当我试图计算数组长度时,错误正在返回.

错误:尝试获取非对象的属性.

任何人都可以帮助我如何进行.

php selenium phpunit selenium-webdriver

0
推荐指数
1
解决办法
2809
查看次数

通过Ansible安装phpunit

我试图通过ansible安装phpunit,以便在vagrant vm上运行它,但是我在构建过程中一直收到错误:

通道"pear.phpunit.de"未初始化,使用"pear channel-discover pear.phpunit.de"在"pear.phpunit.de/PHPUnit"中初始化pear config-set auto_discover 1未知通道"pear.phpunit.de" "无效的包名/包文件"pear.phpunit.de/PHPUnit"安装失败

ansbile配置看起来像:

- name: Install phpunit
  command: pear channel-discover pear.phpunit.de
  command: pear channel-discover pear.symfony-project.com
  command: pear channel-discover components.ez.no
  command: pear channel-discover pear.symfony.com
  command: pear update-channels
  command: pear upgrade-all
  command: pear install pear.symfony.com/Yaml
  command: pear install --alldeps pear.phpunit.de/PHPUnit 
  command: pear install --force --alldeps pear.phpunit.de/PHPUnit
Run Code Online (Sandbox Code Playgroud)

有没有人设法成功通过ansible安装phpunit?

php phpunit vagrant ansible

0
推荐指数
1
解决办法
1564
查看次数

无法在Laravel中运行多个控制器测试

我正在尝试通过编写一些遗留代码的单元测试来清理现有的应用程序(并在整个过程中进行更新).我重写了一些库,我真的很喜欢TDD方法.但是,现在是时候继续测试一些控制器了,我在第一组测试中遇到了问题.我正在按照Jeffery Way的Laravel Testing Decoded解释.

这里的目标是测试我的登录路线:http://my-development-server/login.代码应该像这样工作:首先,检查某人是否已经登录 - 如果是,则将它们重定向到仪表板(应用程序中的主页).否则,渲染登录页面.挺直的.

以下是涉及的路线:

Route::get('login', array(
        'as'        => 'login',
        'uses'      => 'MyApp\Controllers\AccountController@getLogin',
    ));

Route::get('/', array(
        'as'        => 'dashboard',
        'uses'      => 'MyApp\Controllers\DashboardController@showDashboard',
        'before'    => 'acl:dashboard.view',
    ));
Run Code Online (Sandbox Code Playgroud)

这是AccountController::getLogin方法:

public function getLogin()
{
    // Are we logged in?
    if (\Sentry::check())
        return Redirect::route('dashboard');

    // Show the page.
    return View::make('account.login');
}
Run Code Online (Sandbox Code Playgroud)

我正在使用该Sentry库进行用户身份验证.

这是我的第一次测试:

class AccountControllerTest extends TestCase {

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

    public function test_login_alreadyLoggedIn()
    {
        // arrange
        //
        \Sentry::shouldReceive("check")
            ->once() …
Run Code Online (Sandbox Code Playgroud)

php phpunit unit-testing laravel mockery

0
推荐指数
1
解决办法
844
查看次数

Laravel单元测试如何使用电子邮件测试事件而不发送电子邮件

如何在不发送电子邮件的情况下测试此代码段?

public function forgot() 
    {
        $isValid = $this->updateForm->valid(Input::only('email'));
        if ($isValid) {
            $result = $this->user->forgot($this->updateForm->data());
            if (isset($result['user']) && ($result['success'] > 0)) {
                Event::fire('user.mail.forgot', array('data'=>$result['user']));
                return Response::json(array('success'=>1),200);
            } 
            $error = isset($result['error'])?array_pop($result):trans('user.generror');
            return Response::json(array(
              'success'=>0,
              'errors' => array('error'=>array($error))),  
            200);
        }
        return Response::json(array(
                    'success' => 0,
                    'errors' => $this->updateForm->errors()), 
                    200
        );
    }
Run Code Online (Sandbox Code Playgroud)

到现在我测试它:

public function _getSuccess($content)
{
    $json = str_replace(")]}',\n", '', $content);
    $native = json_decode($json);
    return $native->success;
}
public function _set200($method, $uri, $parameters = array())
{
    $this->client->setServerParameter('HTTP_X-Requested-With', 'XMLHttpRequest');
    $response = $this->call($method, $uri, $parameters);
    $this->assertResponseStatus(200); …
Run Code Online (Sandbox Code Playgroud)

phpunit laravel laravel-4

0
推荐指数
1
解决办法
1653
查看次数

PHPUnit willReturnMap方法-回调参数

我的用例比较复杂,但要保持简单:

class MockObject {
    public function test($param1, callable $callback = null) {
        return is_null($callback) ? $param1 : $callback($param1);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想使用returnMap为其他测试模拟该类。

$map = [
    ['a', null, 'a'],
    ['b', $WHAT_SHOULD_BE_HERE?, 'b']
];

$mock = $this->getMock('MockObject');
$mock->expects($this->atLeastOnce())->method('test')->willReturnMap($map);

$this->assertEquals('a', $mock->test('a')); // Works 
$this->assertEquals('b', $mock->test('b', function($value){return $value})); // Doesn't work 
Run Code Online (Sandbox Code Playgroud)

php phpunit mocking

0
推荐指数
1
解决办法
6121
查看次数

在ZF2中PHp单元测试错误'未定义索引:/ config/autoload/global.php中的SERVER_NAME'

我刚开始使用Zend框架2.我想为我的Cart模块设置单元测试.

我按照http://framework.zend.com/manual/current/en/tutorials/unittesting.html的步骤进行了操作

当我运行 :/ var/www/AHA/CDP/module/Cart /测试 来自终端的$ phpunit 我得到以下输出:

Sebastian Bergmann的PHPUnit 3.7.28.

配置从/var/www/ZF2Sample/module/Cart/tests/phpunit.xml中读取

Ë

时间:146毫秒,内存:5.50Mb

有1个错误:

1)Cart\tests\Cart\Controller\CartControllerTest :: testIndexActionCanBeAccessed include(/ var/www/ZF2Sample/module/Admin/config /../ view/error/index.phtml):无法打开流:没有这样的文件或目录

/var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php:506 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php :506 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/View/View.php:205 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/View/View.php:233 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/View/View.php:198 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Mvc/View/Http/DefaultRenderingStrategy.php :102 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:468 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Mvc/View/Http/DefaultRenderingStrategy.php:112/var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager. php:468 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php: 352 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:327/var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase. php:288 /var/www/ZF2Sample/module/Cart/tests/Cart/Controller/CartControllerTest.php:30468 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:352/var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:327 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase.php: 288 /var/www/ZF2Sample/module/Cart/tests/Cart/Controller/CartControllerTest.php:30468 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:352/var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:327 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase.php: 288 /var/www/ZF2Sample/module/Cart/tests/Cart/Controller/CartControllerTest.php:30327 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase.php:288 /var/www/ZF2Sample/module/Cart/tests/Cart/Controller/CartControllerTest.php:三十327 /var/www/ZF2Sample/vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase.php:288 /var/www/ZF2Sample/module/Cart/tests/Cart/Controller/CartControllerTest.php:三十

FAILURES!测试:1,断言:0,错误:1.

下面是我的global.php:

<?php
    define('SITE_URL', 'http://' . $_SERVER['SERVER_NAME'].'/');
    define('JS_URL', 'http://' . $_SERVER['SERVER_NAME'].'/js/');
    define('CSS_URL', 'http://' . $_SERVER['SERVER_NAME'].'/css/');
    define('IMG_URL', 'http://' . $_SERVER['SERVER_NAME'].'/img/');
    return array(
        'cart_webservice_url' …
Run Code Online (Sandbox Code Playgroud)

phpunit zend-framework2

0
推荐指数
1
解决办法
1626
查看次数

持续集成,使用Propel ORM将实际测试数据输入数据库的最佳实践

我使用Propel ORM复制表模式,以便进行持续集成,但Propel只让我得到一个完全充实的模式,它不会让我获得测试数据(或者根本不需要基本的必要数据).

如何从具有版本控制的propel-genPropel ORM生态系统的实时/测试数据库中获取数据?

continuous-integration phpunit propel database-schema

0
推荐指数
1
解决办法
518
查看次数

运行单个测试时找不到PHPUNIT_Framework_TestCase

我正在尝试使用Laravel 5.2.10进行 PHPUnit测试.我在我的项目中本地安装了PHPUnit 5.1.4.

当我跑:

phpunit
Run Code Online (Sandbox Code Playgroud)

PHPUnit test完美地运行我的目录中的所有测试.

但是,当我跑:

phpunit tests/unit/testThatFails.php
Run Code Online (Sandbox Code Playgroud)

我明白了:

PHP Fatal error:  Class 'PHPUNIT_Framework_TestCase' not found in ...
Run Code Online (Sandbox Code Playgroud)

奇怪的是,当我运行phpunit时,它成功运行了测试目录中的每个测试,包括这testThatFails.php很好.

当我尝试运行一次测试时为什么会中断?

更新:
这是我的phpunit.xml:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="bootstrap/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">app/</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
    </php>
</phpunit>
Run Code Online (Sandbox Code Playgroud)

更新:
目前,由于我使用的是Laravel,我通过扩展来避开这个问题TestCase …

php phpunit laravel

0
推荐指数
1
解决办法
1万
查看次数

Laravel PHPUnit始终通过CSRF

我目前正在编写测试,以确保我们的CSRF保护功能可在Laravel中使用。测试看起来像这样。

public function testSecurityIncorrectCSRF()
{
    $this->visit('/login')
     ->type('REDACTED', 'email')
     ->type('123123', 'password');

     session()->regenerateToken();

     $this->press('login')
     ->seePageIs('/login');
}
Run Code Online (Sandbox Code Playgroud)

无论我做什么,即使我传递了错误的_token,登录请求也将始终成功。我已经在PHPUnit测试之外尝试过,并且CSRF保护有效。我所有的中间件都已启用,因此应该启用CSRF保护。

谁能解释为什么会这样?

php phpunit laravel

0
推荐指数
1
解决办法
1452
查看次数