0

我在一个解析一些 xml 的类中有一个方法。如果找到标签<status >failure</status>,则返回异常。

我想构建一个单元测试来检查此方法在 status=failure 时是否返回异常。

目前,我无法使用phpunitMOCKING完成它?

例子:

<?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.
?>

谢谢你的帮助

4

1 回答 1

4

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

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

这可能值得一读:什么是对象模拟,我什么时候需要它?

我认为您实际上是在寻找更多与您的测试类似的东西:

<?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();

?>
于 2013-03-20T10:29:56.283 回答