如何使用PHPUnit进行单元测试异常? [英] How to unit testing Exceptions with PHPUnit?

查看:151
本文介绍了如何使用PHPUnit进行单元测试异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有得到如何使用PHPUnit单元测试异常。



请参阅我的方法与异常:

  public function getPhone ($ html,$ tag ='OFF',$ indication,$ number_lenght){

// ..代码

if($ tag<>'OFF' ){

$ html = $ doc [$ tag] - > text(); // Apanho apenas o texto dentro da TAG
if(empty($ html)){
throw new Exception(Nao foi possivel apanhar qualification texto dentro da TAG,Metodo em causa:getPhone()) ;
}
}

// ..代码
}

现在我的PHPUnit测试:

 <?php 

require_once '../Scrap.php';

class ScrapTest扩展PHPUnit_Framework_TestCase
{

protected $ scrap;

//安装函数实例化对象$ this-> scrap
protected function setUp()
{
$ this-> scrap = new Scrap ;
}

/ **
* @covers Scrap :: getPhone
* @expectedException异常
*
* /
public function testGetPhone(){

// Variables1
$ array_static1 = Array(0 => 218559372,1 => 927555929,2 => 213456789,3 => 912345678) ;
$ phone_list1 ='< / div> A前面< br />< br />< br />< br />< br />< br /> ; -Apoio;< br />-CIAção;< br /> -Campanhas;< br />-Promoções< br />< br />< br />CONDIÇESES:< ; br />< br /> Local de Trabalho:Es< br /> Folgas:Mistas< br />< br />< br />< br /> ordem 500€ < br />< br />< br />< br />Mínimos:< br />< br /> - Conhecimentos;< br /> < br/>-INGLÊS.<br/>< br />< br />< br /> Candidaturas:< br /> .email@ffff.es<br /> ; 218559372 | 927 555 929 | < br /> RH< br /> Rua C. Sal。 40< br /> 1000-000里斯本< br />< br />< br /> +351 21 3456789 | (351)912345678';

//变量2
$ array_static2 = Array(0 =>'NA');
$ phone_list2 =;

// ..更多测试

//测试异常,未找到标签
如果(TRUE){

// Bloco get $($ phone_list1,'hr','351','9'); $ {
$ this-> scrap-> getPhone
}
catch(异常$ expected){
return;
}

$ this-> fail('一个预期的异常未被提出。
}



}
}
?>

如果我运行测试,我得到失败:

  1)ScrapTest :: testGetPhone 
预期的异常异常

失败!
测试:1,断言:5,失败:1.

异常引发但我不想在PHPUnit中失败,如果异常提高,我想要测试OK。



你能给我一些线索吗?



最好的问候,

解决方案

你在那里做得太多了。

以太网使用:@expectedException异常



:尝试/ catch / $ this-> fail



现在,您正在做的这个方法现在说捕获该异常,然后期望代码再次抛出!



在我看来,第一种方法是更干净,因为它只有5行(甚至更多)代码行,而且不太容易出错。

  / ** 
* @covers Scrap :: getPhone
* @expectedException异常
*
* /
public function testGetPhone(){

// Variables1
$ array_static1 = Array(0 => 218559372,1 => 927555929,2 => 213456789,3 => 912345678);
$ phone_list1 ='...';

//变量2
$ array_static2 = Array(0 =>'NA');
$ phone_list2 =;

// .. more tests

// Bloco try / catch para confirmar que aquilançaexcepção
$ this-> scrap-> getPhone($ phone_list1,'hr','351','9');

应该这样做。


I'm not getting how to unit test Exceptions with PHPUnit.

Please see my method with the Exception:

    public function getPhone($html, $tag = 'OFF', $indicative, $number_lenght) {

        // .. code

        if ($tag <> 'OFF') {

            $html = $doc[$tag]->text(); // Apanho apenas o texto dentro da TAG
                if (empty($html)) {
                    throw new Exception("Nao foi possivel apanhar qualquer texto dentro da TAG, Metodo em causa: getPhone()");
                }               
        }

        // .. code
    }

And now my PHPUnit Test:

<?php

require_once '../Scrap.php';

class ScrapTest extends PHPUnit_Framework_TestCase
{

    protected $scrap;

    // Setup function to instantiate de object to $this->scrap
    protected function setUp()
    {
        $this->scrap = new Scrap;
    }

    /**
    * @covers Scrap::getPhone
    * @expectedException Exception
    *
    */
    public function testGetPhone() {

        // Variables1
        $array_static1 = Array(0 => 218559372, 1 => 927555929, 2 => 213456789, 3 => 912345678);
        $phone_list1   = '</div>A Front para<br /><br /><br /><br /><br /><br />-Apoio;<br />-Criação;<br />-Campanhas;<br />-Promoções<br /><br /><br />CONDIÇÕES:<br /><br />Local de Trabalho: Es<br />Folgas: Mistas<br /><br /><br /><br />ordem 500€<br /><br /><br /><br />Mínimos:<br /><br />- Conhecimentos;<br />- Ensino ;<br />-INGLÊS.<br /><br /><br /><br />Candidaturas: <br />email@ffff.es<br />218559372 | 927 555 929 | <br />RH<br />Rua C. Sal. 40<br />1000-000 Lisboa<br /><br /><br />+351 21 3456789 | (351) 912345678';

        // Variables2
        $array_static2 = Array(0 => 'NA');
        $phone_list2   = "";

        // .. more tests

        // Test Exception, Tag not found
        if (TRUE) {

            // Bloco try/catch para confirmar que aqui lança excepção
            try {            
                    $this->scrap->getPhone($phone_list1, 'hr', '351', '9');        
                }         
            catch (Exception $expected) {
                    return;        
                }         

            $this->fail('An expected exception has not been raised.');  
        }



    }
}
?>

If I run the test I got "Failure":

1) ScrapTest::testGetPhone
Expected exception Exception

FAILURES!
Tests: 1, Assertions: 5, Failures: 1.

The exception raises but I don't want to get failure in the PHPUnit, If the Exception raise, I want to get the test OK.

Can you give me some clues?

Best Regards,

解决方案

You are doing too much there.

Ether use: @expectedException Exception

OR: try / catch / $this->fail

The way you are doing it right now says "catch that exception and THEN expect the code to throw another one!"

The first way is cleaner in my opinion because it's only 1 line against 5 (or even more) lines of code and it's less error prone.

/**
* @covers Scrap::getPhone
* @expectedException Exception
*
*/
public function testGetPhone() {

    // Variables1
    $array_static1 = Array(0 => 218559372, 1 => 927555929, 2 => 213456789, 3 => 912345678);
    $phone_list1   = '...';

    // Variables2
    $array_static2 = Array(0 => 'NA');
    $phone_list2   = "";

    // .. more tests

    // Bloco try/catch para confirmar que aqui lança excepção
    $this->scrap->getPhone($phone_list1, 'hr', '351', '9');        

That should do it.

这篇关于如何使用PHPUnit进行单元测试异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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