标签: phpunit

闭包内的嘲讽模拟方法

我在call_user_func()示例调用的闭包内有问题的单元测试方法:

public function trans($lang, $callback)
{
   $this->sitepress->switch_lang($lang);
   call_user_func($callback);
}
Run Code Online (Sandbox Code Playgroud)

在控制器上:

public function sendMail()
{
   $foo = $baz = 'something';
   $mail = $this->mailer;
   $this->helper->trans_c('en', function() use($foo, $baz, $mail) {
      $mail->send('Subject', $foo, $baz);
   });
}
Run Code Online (Sandbox Code Playgroud)

测试用例 :

public function testSomething()
{
   $helperMock = Mockery::mock('Acme\Helper');
   $helperMock->shouldReceive('trans_c')->once(); // passed

   $mailMock = Mockery::mock('Acme\Mail');
   $mailMock->shouldReceive('send')->once(); // got should be called 1 times instead 0

   $act = new SendMailController($helperMock, $mailMock);
   $act->sendMail();
}
Run Code Online (Sandbox Code Playgroud)

如何确保->send()在闭包内调用该方法trans_c()

我试过

$helperMock->shouldReceive('trans_c')->with('en', function() use($mailMock) {
   $mailMock->shouldReceive('send');
});
Run Code Online (Sandbox Code Playgroud)

没运气。:(

好吧,通过传入 …

phpunit unit-testing mocking mockery laravel-4

3
推荐指数
1
解决办法
2230
查看次数

使用私有方法正确测试一个简单的类

描述: 我有一个简单的类,它创建一个指向上传文件目录的符号链接,这些文件仅供注册会员使用。它使用当前用户的会话 ID 为用户生成随机目录。一旦用户注销,符号链接就会被删除。我想对类的功能进行单元测试。

问题: 由于大多数函数都是私有的,而且我认为没有任何理由将它们公开,我该如何正确地对此类进行单元测试?

这是 PHP 类的代码:

<?php

namespace Test\BackEnd\MemberBundle\Library;


use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\KernelInterface;

class DirectoryProtector
{
/** @var SessionInterface $_session */
private $_session;

/** @var ContainerInterface $_kernel */
private $_kernel;

/**
 * @param SessionInterface $session
 * @param KernelInterface $kernel
 */
public function __construct( SessionInterface $session, KernelInterface $kernel )
{
    $this->_session = $session;
    $this->_kernel = $kernel;
}

/**
 * @param bool|false $protect
 * Public method to symlink directories
 */
public function protectDirectory($protect = FALSE)
{

    if ($protect) { …
Run Code Online (Sandbox Code Playgroud)

php phpunit unit-testing symfony

3
推荐指数
1
解决办法
2645
查看次数

如何有效地拆分大型 phpunit 测试套件?

我使用 phpunit 的 testsuites 功能来组织我的测试。我这样做是为了以后能够并行运行测试。

对于不同的目录,这相对简单。因此,例如,我可以通过捆绑来拆分测试套件。

<testsuite name="bundle-one">
    <directory>tests/BundleOne</directory>
</testsuite>

<testsuite name="bundle-two">
    <directory>tests/BundleTwo</directory>
</testsuite>

<testsuite name="bundle-three">
    <directory>tests/BundleThree</directory>
</testsuite>
Run Code Online (Sandbox Code Playgroud)

但是现在我有一个包含数十个子文件夹的目录(服务)。我可以手动为这个文件夹制作几个测试套件。但在我看来,这将是一个薄弱的解决方案。因为如果我提到测试套件中的每个子文件夹并且文件夹被重命名或删除,测试套件可能很容易损坏。

我的想法是使用某种正则表达式来选择一系列子文件夹以包含在一个测试套件中,并为另一个测试套件选择另一范围的文件夹。

<testsuite name="services-AM">
    <directory>tests/services/{A-M}</directory>
</testsuite>

<testsuite name="services-NZ">
    <directory>tests/services/{A-M}</directory>
</testsuite>
Run Code Online (Sandbox Code Playgroud)

我找不到任何关于我的想法的文档。有人可能对此有想法吗?:-)

phpunit test-suite

3
推荐指数
1
解决办法
937
查看次数

PHPUnit:模拟 PDOException-&gt;getMessage() 方法

我写一个基本的PDO包装类,当我想以模拟异常抛出的PDOStatement::prepare()使用willThrowException()与模拟PDOException在我的单元测试,返回的值getMessage()始终是空字符串,而不是我的设置。

这是我尝试的方法:

// WrapperClass.php
<?php 

class WrapperClass
{

    private $pdo;
    private $error = '';

    public function __construct(\PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function save()
    {
        $sql = 'INSERT INTO ...';

        try {
            $this->pdo->prepare($sql);

            // some value binding and executing the statement
        } catch (\PDOException $pdoException) {
            $this->error = $pdoException->getMessage();
        }
    }

    public function getError()
    {
        return $this->error;
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的测试:

// WrapperClassTest.php
<?php 

class WrapperClassTest extends \PHPUnit_Framework_TestCase
{

    /**
     * …
Run Code Online (Sandbox Code Playgroud)

php phpunit exception mocking

3
推荐指数
1
解决办法
1025
查看次数

“require_once”语句的 PHPUnit 代码覆盖率

我可以从代码覆盖率中排除“require_once”语句吗?带有“require_once”的行被报告为未覆盖,但如果脚本中的其他行被覆盖,则不可能:

在此处输入图片说明

PHP 7.0.11、PHPUnit 5.5.7 和 XDebug 2.4.0 用于代码覆盖。

php phpunit code-coverage xdebug

3
推荐指数
1
解决办法
478
查看次数

如何模拟另一个类使用的全局函数和类

我正在尝试编写一个测试,我的一个方法使用了一个全局函数web(),该函数采用(字符串)url,并创建并返回UrlHelper. 这为我的应用程序提供了一些辅助方法的快捷方式。(是的 DI 会更好,但这是在幼虫应用程序中......)

我正在尝试测试的方法使用这个全局助手来获取给定 url 的内容并将其与另一个字符串进行比较。

使用 phpunit,我如何拦截对 的调用web或创建,UrlHelper以便确保它返回给定的响应?代码看起来有点像下面

function web($url){
 return new \another\namespace\UrlUtility($url);
}
Run Code Online (Sandbox Code Playgroud)

...

namespace some/namespace;

class checker {
   function compare($url, $content){
       $content = web($url)->content();
       ...logic...
       return $status;
   }
}
Run Code Online (Sandbox Code Playgroud)

单元测试正在测试比较的逻辑,所以我想从web调用中获取预期的内容。我希望模拟/存根可以解决问题 - 但我不确定我是否可以点击这个全局函数或另一个未传入的类?

谢谢

php testing phpunit unit-testing

3
推荐指数
1
解决办法
6084
查看次数

PHPUnit 弃用警告未通过测试

我在 PHP 5.3.29 安装上使用 PHPUnit 4.8。我们应用程序中的一些代码使用了弃用的mysql_*功能,PHPUnit 将这些实例的弃用通知转换为异常,从而使那些特定的测试用例失败。

现在我已经将 包含convertErrorsToExceptions="false"在 config.xml 中,但这似乎没有帮助,因为它仍在发生。

任何人都可以帮助阐明这里可能发生的事情吗?

干杯!

编辑:在gist.github.com上添加了示例文件

php configuration phpunit exception deprecated

3
推荐指数
2
解决办法
4575
查看次数

Laravel dusk 报告“一般错误:5 数据库被锁定”和“操作超时”

我正在运行脚本

namespace Tests\Browser;

use App\User;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\RefreshDatabase;

class RegistrationTest extends DuskTestCase
{

    use RefreshDatabase;

    /** @test */

    public function a_user_registers_for_an_account()
    {
        $this->browse(function (Browser $browser)
        {
            $browser->visit(route('app-registration-create'))
                ->type('name', 'John')
                ->type('lastName', 'Doe')
                ->type('email', 'john.doe@ps.com')
                ->type('password', 'password')
                ->type('password_confirmation', 'password')
                ->click('@dusk-accept')
                ->click('@register-button') //
                ->assertDontSee('The name field is required.');
        });

        $this->assertDatabaseHas('users', [
            'email' => 'john.doe@ps.com',
            'verified' => 0
        ]);
    }


    /** @test */

    public function a_user_confirms_a_email_address()
    {
        $this->browse(function (Browser $browser)
        {
            $user = User::where('email', 'john.doe@ps.com')->first();

            var_dump(route('app-registration-confirm-email', ['token' => $user->token])); // "http://ps.dev/app/registration/confirm/aPAWN1QlGyl8Id2vXIJU9Fn8G6bsef" …
Run Code Online (Sandbox Code Playgroud)

phpunit laravel laravel-dusk

3
推荐指数
1
解决办法
970
查看次数

捕获 ArgumentCountError 和 PHPUnit_Framework_Error_Warning

有人提交pull请求我的一个库,其中一个参数作出更换像可选function doSomething($var)function doSomething($var = 'whatever')

因此,我添加了一个单元测试,以确保如果您没有将足够的变量传递给该方法,则会发出错误。为了抓住这一点,我使用了 PHPUnit 注释@expectedException。对于 PHP 7.0,预期的异常是,PHPUnit_Framework_Error_Warning但对于 PHP 7.1+,预期的异常是ArgumentCountError. 这提出了一个小问题。我可以让测试通过 PHP 7.0 及更早版本或通过 PHP 7.1 及更高版本。我不能让他们都支持。

另一个 PHPUnit 注释是,@requires但它似乎只允许您将测试限制为最低 PHP 版本 - 而不是最高 PHP 版本。例如。如果我这样做@requires PHP 7.1,则意味着 PHP 7.1 是运行测试所需的最低 PHP 版本,但无法使 PHP 7.0 成为运行测试的最高版本。

我认为这样做@expectedException Exception会起作用(因为大概PHPUnit_Framework_Error_Warning并且ArgumentCountError两者都扩展了 Exception 但似乎也不是这种情况。

如果我可以做类似的事情会很酷,@expectedException PHPUnit_Framework_Error_Warning|ArgumentCountError但 PHPUnit 文档中的任何内容都没有让我相信我可以并且https://github.com/sebastianbergmann/phpunit/issues/2216让它听起来像是无法完成时期。

也许我应该一起删除这个特定的单元测试?

php phpunit unit-testing

3
推荐指数
1
解决办法
1137
查看次数

使用 PHPUnit 断言异常

我有一个函数来计算一个平方的值,我想对此进行测试。

函数平方是这样的:

 public function squaring($number)
    {
        if ($number == 0) {
            throw new InvalidDataException("0 can't be squared");
        }

        return $number * $number;
    }
Run Code Online (Sandbox Code Playgroud)

测试的第一步是检查它是否正确:

  public function testIfSquaringIsCorrect()
    {
        $number = 2;

        $result = $this->modelPractice->squaring($number);

        $this->assertEquals(4, $result);
    }
Run Code Online (Sandbox Code Playgroud)

最后一步检查我是否收到异常。

我该怎么做?

我像这样尝试但它不起作用:

  public function testSquaringLaunchInvalidDataException()
{
    $number = 0;

    $result = $this->modelPractice->squaring($number);

    $expected = $this->exceptException(InvalidDataException::class);

    $this->assertEquals($expected, $result);
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

php testing phpunit

3
推荐指数
1
解决办法
7556
查看次数