PHPUnit使用名为"Method"的方法测试和抽象类 [英] PHPUnit test and abstract class with a method named 'Method'

查看:90
本文介绍了PHPUnit使用名为"Method"的方法测试和抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试具有名为Method的方法的抽象类.

I am in the process of testing an abstract class that has a method called Method.

这是我的抽象类(节略):

Here is my abstract class (abridged):

abstract class ClassToTest {

  function Method($_value = NULL) {
    // based on the value passed in a different value is returned.
  }
}

这是我的PHPUnit类:

Here is my PHPUnit class:

class ClassToTestTest extends PHPUnit_Framework_TestCase {
  public $object = NULL;

  public function setUp() {
    $this->object = $this->getMockForAbstractClass('ClassToTest');
  }

  public function testMethod() {

    // passing no value should return NULL
    $this->assertNull($this->object->Method());

    // passing a value should return a value
    $this->assertEquals($this->object->Method($method), 'return_value');
  }
}

基于 PHPUnit文档,我应该能够使用

$stub->expects($this->any())->method('Method')->willReturn('foo');

不知何故,但我不知道该如何做.

somehow, but I cannot figure out how to make this work.

如何使用PHPUnit测试称为Method的方法?

How can I use PHPUnit to test a method called Method?

此外,我没有选择将该方法重命名为其他名称的选项.

Also, I don't have the option to rename the method to something else.

推荐答案

您正在测试的类肯定是​​您不应该嘲笑的唯一类.如果您伪造了它的方法调用,您将不会真正对其进行测试.

Class you're testing is surely the only class you shouldn't be mocking. You wouldn't be really testing it if you faked its method calls.

由于您的类是抽象的,因此您需要通过具体的实现对其进行测试.如果您还没有,请为测试创建它.

Since your class is abstract you need to test it through a concrete implementation. If you don't have one, create it for the test.

class MyClassToTest extends ClassToTest
{
    // implement abstract methods
}

class ClassToTestTest extends PHPUnit_Framework_TestCase
{
    private $object;

    protected function setUp()
    {
        $this->object = new MyClassToTest();
    }

    public function testMethod()
    {
        $this->assertSame('return_value', $this->object->Method('foo'));
    }

}

这篇关于PHPUnit使用名为"Method"的方法测试和抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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