phpunit mock一个应该返回异常的方法

时间:2013-03-20 10:15:12

标签: xml exception mocking phpunit

我在类中有一个解析一些xml的方法。 如果找到标签<状态>失败< / status> ,它会返回异常。

我想构建一个unittest,检查此方法在status = failure时返回异常。

目前,我无法使用 phpunit MOCKING 完成任务?

示例:

<?php
$mock = $this->getMock('Service_Order_Http', array('getResponse'));
        $mock->expects($this->any())
            ->method('getResponse')
            ->will($this->throwException(new Exception()));

        $e = null;
        try {
            $mock->getResponse();
        } catch (Exception $e) {

        }
        $this->assertTrue($e instanceof Exception, "Method getResponse should have thrown an exception");

//phpunit sends back: PHPUnit_Framework_ExpectationFailedException : Failed asserting that exception of type "Exception" is thrown.
?>

感谢您的帮助

1 个答案:

答案 0 :(得分:4)

我认为你在单元测试中误解了模拟的目的。

模拟用于替换您实际尝试测试的类的依赖项。

这可能值得一读:What is Object Mocking and when do I need it?

我认为你实际上正在寻找更多的测试内容:

<?php

    // This is a class that Service_Order_Http depends on.
    // Since we don't want to test the implementation of this class
    // we create a mock of it.
    $dependencyMock = $this->getMock('Dependency_Class');

    // Create an instance of the Service_Order_Http class,
    // passing in the dependency to the constructor (dependency injection).
    $serviceOrderHttp = new Service_Order_Http($dependencyMock);

    // Create or load in some sample XML to test with 
    // that contains the tag you're concerned with
    $sampleXml = "<xml><status>failure</status></xml>";

    // Give the sample XML to $serviceOrderHttp, however that's done
    $serviceOrderHttp->setSource($sampleXml);

    // Set the expectation of the exception
    $this->setExpectedException('Exception');

    // Run the getResponse method.
    // Your test will fail if it doesn't throw
    // the exception.
    $serviceOrderHttp->getResponse();

?>