2015-01-27 40 views
-1

我有以下代码来测试类构造函数是否会触发异常但PHPUnit测试失败。我想弄清楚我做错了什么。测试PHPUnit测试“__construct()必须是..的一个实例”不能识别异常

/** @test */ 
public function should_require_instance_of_uuid() 
{ 
    $this->setExpectedException('Exception'); 
    $id = new BusinessPartnerId; 
} 

PHPUnit的提供了以下错误: 有1个错误: 1)测试\域\型号\ COMMON \业务伙伴\ BusinessPartnerIdTest :: should_require_instance_of_uuid 参数1传递给域\型号\ COMMON \业务伙伴\ BusinessPartnerId :: __ construct()必须是Rhumsaa \ Uuid \ Uuid的一个实例,没有给出,在第14行的tests/Comain/Model/Common/BusinessPartner/BusinesPartnerIdTest.php中调用,并且定义为

Domain/Model/Common/BusinessPartner /BusinessPartnerId.php:20 tests/Domain/Model/Common/BusinessPartner/BusinesPartnerIdTest.php:14

我不知道为什么这个测试没有通过?我也曾尝试: $this->setExpectedException('InvalidArgumentException');

回答

1

您的测试应该长相:

如果你有类:

class Stack 
{ 
    public function __construct(\Model $model) 
    { 
    } 
} 

然后测试:

/** 
* @test 
*/ 
public function shouldCheckInstance() 
{ 
    try { 
     new Stack(null); 
    } catch(\Exception $e) { 
     $this->assertContains('must be an instance of Model', $e->getMessage()); 
    } 
} 
+0

这个工作!谢谢。 –

0

虽然我还没有与当前工作PHPUnit,旧版本不允许你捕获基本的异常,但会捕获你自己的扩展到Exception类。另外,这个异常可能是命名空间的,所以它是\ Exception,而不仅仅是Exception。

我还在文档块中使用了@expectedException来指示我期待的异常。

/** 
* @test 
* @expectedException \MyNamespace\MyException 
*/ 
public function shouldCheckInstance() 
{ 
    new MyClass(): 
} 

/** 
* @test 
*/ 
public function shouldCheckInstance() 
{ 
    $this->setExpectedException('\MyNamespace\MyException'); 
    new MyClass(): 
}