phpunit 自定义断言需要帮助

发布于 2024-12-28 10:01:08 字数 1936 浏览 4 评论 0原文

我正在尝试按照本教程向 phpunit 添加自定义断言,验证作为字符串返回的复数(例如

“-123+456i”

(通过我正在测试的方法)达到实部和虚部的定义精度。我已经放置了一个 Complex.php 类来将字符串解析为实部和虚部,并将以下断言类放在一起作为 complexAssert.php:

require_once 'PHPUnit/Framework/Assert.php';
include_once getcwd().'/custom/Complex.php';

class complexAssert extends PHPUnit_Framework_Assert {

    public function assertComplexEquals($expected, $actual, $message = '', $delta = 0)
    {
        $expectedComplex = new Complex($expected);
        $actualComplex = new Complex($actual);

        if (!($actualComplex->getReal() >= ($expectedComplex - $delta) &&
            $actualComplex->getReal() <= ($expectedComplex + $delta))) {
            return $this->fail($message);
        }

        if (!($actualComplex->getImaginary() >= ($expectedComplex - $delta) &&
            $actualComplex->getImaginary() <= ($expectedComplex + $delta))) {
            return $this->fail($message);
        }

    }
}

我的单元测试脚本:

require_once getcwd().'/custom/complexAssert.php';
require_once 'testDataFileIterator.php';

class EngineeringTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider providerIMSUM
     */
    public function testIMSUM()
    {
        $args = func_get_args();
        $expectedResult = array_pop($args);
        $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSUM'),$args);
        $this->assertComplexEquals($expectedResult, $result);
    }

    public function providerIMSUM()
    {
        return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSUM.data');
    }
}

当我只是做了一个assertEquals...但现在我添加了包含并更改为我的新断言,它崩溃了,声称它无法调用未定义的方法assertComplexEquals()。

有没有人成功地使用自定义断言扩展 phpunit,并且可以看到我做错了什么?

I'm trying to add a custom assert to phpunit, following this tutorial, to validate complex numbers returned as a string (e.g.

"-123+456i"

by the method that I'm testing) to a defined precision for both the real and imaginary components. I've put a Complex.php class to parse the string into the real and imaginary parts, and put together the following assertion class as complexAssert.php:

require_once 'PHPUnit/Framework/Assert.php';
include_once getcwd().'/custom/Complex.php';

class complexAssert extends PHPUnit_Framework_Assert {

    public function assertComplexEquals($expected, $actual, $message = '', $delta = 0)
    {
        $expectedComplex = new Complex($expected);
        $actualComplex = new Complex($actual);

        if (!($actualComplex->getReal() >= ($expectedComplex - $delta) &&
            $actualComplex->getReal() <= ($expectedComplex + $delta))) {
            return $this->fail($message);
        }

        if (!($actualComplex->getImaginary() >= ($expectedComplex - $delta) &&
            $actualComplex->getImaginary() <= ($expectedComplex + $delta))) {
            return $this->fail($message);
        }

    }
}

My unit test script:

require_once getcwd().'/custom/complexAssert.php';
require_once 'testDataFileIterator.php';

class EngineeringTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider providerIMSUM
     */
    public function testIMSUM()
    {
        $args = func_get_args();
        $expectedResult = array_pop($args);
        $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSUM'),$args);
        $this->assertComplexEquals($expectedResult, $result);
    }

    public function providerIMSUM()
    {
        return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSUM.data');
    }
}

The unit tests worked without error (but failed) when I was simply doing an assertEquals... but now I've added the include and changed to my new assert, it's crashing claiming that it can't call the undefined method assertComplexEquals().

Has anybody had any success extending phpunit with custom asserts, and can see what I'm doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

动听の歌 2025-01-04 10:01:08

显然,让 $this->someCustomAssertion 工作的唯一方法是扩展 PHPUnit_Framework_TestCase 并在那里创建包装方法,或者静态调用自定义断言。

例如,Zend Framework 只是使用附加方法(断言)扩展 PHPUnit_Framework_TestCase

Obviously the only way to get $this->someCustomAssertion worked is to extend PHPUnit_Framework_TestCase and create wrapper-methods there, or call your custom assertions statically.

Zend Framework, for example, just extends PHPUnit_Framework_TestCase with additional methods (assertions)

瀟灑尐姊 2025-01-04 10:01:08

最后,我选择不扩展现有的断言,而是修改复杂的断言逻辑以返回一个简单的布尔值,然后可以使用assertTrue()对其进行测试,并使用可以使用简单的getMessage()检索的错误消息用于在 phpunit 结果中显示。说实话,用这种方式感觉容易多了

include_once __DIR__.'/Complex.php';

class complexAssert {

    private $_errorMessage = '';

    public function assertComplexEquals($expected, $actual, $delta = 0)
    {
        $expectedComplex = new Complex($expected);
        $actualComplex = new Complex($actual);

        if ($actualComplex->getReal() < ($expectedComplex->getReal() - $delta) ||
            $actualComplex->getReal() > ($expectedComplex->getReal() + $delta)) {
            $this->_errorMessage = 'Mismatched Real part: ' .
                                   $actualComplex->getReal() . 
                                   ' !== ' . 
                                   $expectedComplex->getReal();
            return FALSE;
        }

        if ($actualComplex->getImaginary() < ($expectedComplex->getImaginary() - $delta) ||
            $actualComplex->getImaginary() > ($expectedComplex->getImaginary() + $delta)) {
            $this->_errorMessage = 'Mismatched Imaginary part: ' .
                                   $actualComplex->getImaginary() . 
                                   ' !== ' . 
                                   $expectedComplex->getImaginary();
            return FALSE;
        }

        return TRUE;
    }

    public function getErrorMessage() {
        return $this->_errorMessage;
    }
}

我的单元测试脚本:

//  Custom assertion class for handling precision of Complex numbers
require_once __DIR__.'/../../custom/complexAssert.php';
//  Data Provider handler
require_once 'testDataFileIterator.php';

class EngineeringTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider providerIMSUM
     */
    public function testIMSUM()
    {
        $args = func_get_args();
        $expectedResult = array_pop($args);
        $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSUM'),$args);
        $complexAssert = new complexAssert();
        $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
                          $complexAssert->getErrorMessage());
    }

    public function providerIMSUM()
    {
        return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSUM.data');
    }
}

并且记录的 phpunit 结果足够清晰:

3) EngineeringTest::testIMSUB with data set #7 ('-12.34-5.67i', '-123.45-67.89', '#NUM!')
Mismatched String: 111.11 !== #NUM!
Failed asserting that false is true.

In the end, I chose not to extend existing asserts, but to modify my complex assertion logic to return a simple boolean, that could then be tested using assertTrue(), and with an error message that could be retrieved with a simple getMessage() for display in the phpunit results. To be honest, it feels a whole lot easier to use this way

include_once __DIR__.'/Complex.php';

class complexAssert {

    private $_errorMessage = '';

    public function assertComplexEquals($expected, $actual, $delta = 0)
    {
        $expectedComplex = new Complex($expected);
        $actualComplex = new Complex($actual);

        if ($actualComplex->getReal() < ($expectedComplex->getReal() - $delta) ||
            $actualComplex->getReal() > ($expectedComplex->getReal() + $delta)) {
            $this->_errorMessage = 'Mismatched Real part: ' .
                                   $actualComplex->getReal() . 
                                   ' !== ' . 
                                   $expectedComplex->getReal();
            return FALSE;
        }

        if ($actualComplex->getImaginary() < ($expectedComplex->getImaginary() - $delta) ||
            $actualComplex->getImaginary() > ($expectedComplex->getImaginary() + $delta)) {
            $this->_errorMessage = 'Mismatched Imaginary part: ' .
                                   $actualComplex->getImaginary() . 
                                   ' !== ' . 
                                   $expectedComplex->getImaginary();
            return FALSE;
        }

        return TRUE;
    }

    public function getErrorMessage() {
        return $this->_errorMessage;
    }
}

My unit test script:

//  Custom assertion class for handling precision of Complex numbers
require_once __DIR__.'/../../custom/complexAssert.php';
//  Data Provider handler
require_once 'testDataFileIterator.php';

class EngineeringTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider providerIMSUM
     */
    public function testIMSUM()
    {
        $args = func_get_args();
        $expectedResult = array_pop($args);
        $result = call_user_func_array(array('PHPExcel_Calculation_Engineering','IMSUM'),$args);
        $complexAssert = new complexAssert();
        $this->assertTrue($complexAssert->assertComplexEquals($expectedResult, $result, 1E-8),
                          $complexAssert->getErrorMessage());
    }

    public function providerIMSUM()
    {
        return new testDataFileIterator('rawTestData/Calculation/Engineering/IMSUM.data');
    }
}

and the logged phpunit result is clear enough:

3) EngineeringTest::testIMSUB with data set #7 ('-12.34-5.67i', '-123.45-67.89', '#NUM!')
Mismatched String: 111.11 !== #NUM!
Failed asserting that false is true.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文