【问题标题】:phpunit mock a method that should return an exceptionphpunit 模拟一个应该返回异常的方法
【发布时间】:2013-03-09 09:06:38
【问题描述】:

我在一个类中有一个方法可以解析一些 xml。 如果找到标签failure,则返回异常。

我想构建一个单元测试来检查此方法在 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.
?>

感谢您的帮助

【问题讨论】:

  • 重新阅读您的问题后; “Service_Order_Http”是您要测试的类吗?
  • 是的,“Service_Order_Http”是我要模拟的类。包含xml解析方法的那个。
  • 我已经更新了我的答案,希望这就是你所追求的。

标签: xml exception mocking phpunit


【解决方案1】:

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

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

这可能值得一读: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();

?>

【讨论】:

  • 谢谢 Dan,这行得通,但是我的 xml 解析呢? getResponse() 应该只在 xml 标签 failure 的情况下返回一个异常,在你的情况下,它总是返回一个异常。
  • 再次感谢,差不多了,因为我没有 setSource() :) 我需要在不使用 setSource() 的情况下传递 $sampleXml,这就是我考虑模拟的原因。
  • Service_Order_Http在正常运行时如何获取xml?
  • 使用 Zend_Http_Client 的受保护方法。 protected 方法将响应 xml 设置为受保护的 var,将由 getResponse()
  • 一次测试应该在状态下测试失败,并返回异常。然后使用另一个可能的模拟对象完成另一个测试用例,以处理成功。
猜你喜欢
  • 1970-01-01
  • 2017-02-12
  • 2014-11-07
  • 2016-03-21
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
相关资源
最近更新 更多