dongyue0263 2019-07-17 06:33
浏览 92
已采纳

PHP单元测试无法通过所有测试

I am creating a class with some unit tests, but i am not able to pass few tests. Example is shown below.

Unit Test

class OffsetTest extends \PHPUnit\Framework\TestCase
{


   /**
    * @dataProvider getIllegalOffsets
    * @expectedException \InvalidArgumentException
    * @param $offset
    */
   public function testIllegalParameters($offset)
    {
        new \OffsetEncodingAlgorithm($offset);

        $this->fail('Exception should be thrown');
    }
    /**
     * Data provider for {@link OffsetTest::testIllegalParameters()}
     * @return array
     */
    public function getIllegalOffsets()
    {
        return [
            [-1],
        ];
    }
}

My Class

<?php

class Offset
{
    public function __construct(int $offset = 13)
    {
       try {
            if ($offset < 0) {
                throw new Exception('Exception should be thrown');
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
        $this->offset = $offset;
    }
}

This how the test progress go enter image description here

I want all to be passed

  • 写回答

1条回答 默认 最新

  • duanli4146 2019-07-17 10:59
    关注

    While testing for the testIllegalParameters() which expects an exception in return, you don't have to use try-catch block. Just throw an exception in an if condition simply.

    Secondly throw a correct type of exception that is defined in the test case InvalidArgumentException

    class Offset
    {
        public function __construct(int $offset = 13)
        {
            if ($offset < 0) {
                throw new InvalidArgumentException('Offset should be greater than equal to zero');
            } else {
                $this->offset = $offset;
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏