phpunit测试ExpectedException无法正常工作 [英] phpunit testing expectedException not working

查看:121
本文介绍了phpunit测试ExpectedException无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为InvalidArgumentException测试我的班级,但得到

I am trying to test my class for InvalidArgumentException but I get

Tests \ BarTest :: should_receive_parameter缺少参数1 Itdc \ Foo \ Bar :: __ construct(),在 第10行上的/mypath/foo/tests/BarTest.php和 定义

Tests\BarTest::should_receive_parameter Missing argument 1 for Itdc\Foo\Bar::__construct(), called in /mypath/foo/tests/BarTest.php on line 10 and defined

这是我使用的测试(BarTest.php)文件:

This is the test (BarTest.php) file I use:

<?php namespace Tests;
use Itdc\Foo\Bar;
class BarTest extends \PHPUnit_Framework_TestCase {
    /** @test */
    public function should_receive_parameter() {
        $this->setExpectedException('Exception');
        $id = new Bar;
    }
}

这是Bar类:

<?php namespace Itdc\Foo;
class Bar {
    public function __construct($a) {
        // do something
    }
}

我尝试在评论部分放入setExpectedException,也尝试使用InvalidArgumentException,但是没有运气.

I have tried to puth setExpectedException in comment section, also tried to use InvalidArgumentException, but no luck.

任何暗示我做错了事.

推荐答案

如果直接捕获它,则可以var_dump()异常.

If you catch it directly you can var_dump() the exception.

/** @test */
public function shouldThrowException() {
  try {
    new Foo();
  } catch (\Exception $e) {
    var_dump($e);
  }
}

输出:

class PHPUnit_Framework_Error_Warning#19 (9) {
  ...

因此,这里的源代码不会触发异常,而是会引发错误,PHPUnit会将错误转换为特定的异常.但是它没有包含在断言中.

So here the source does not trigger an exception but an error, PHPUnit converts the error into a specific exception. But it does not include it in the assertions.

尝试使用特定的异常名称:

Try using the specific exception name:

/** @test */
public function shouldThrowException() {
  $this->setExpectedException('PHPUnit_Framework_Error_Warning');
  new Foo();
}

这篇关于phpunit测试ExpectedException无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆