测试抽象类 [英] Testing Abstract Classes

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

问题描述

如何使用PHPUnit测试抽象类的具体方法?

How do I test the concrete methods of an abstract class with PHPUnit?

我希望我必须在测试中创建某种对象.不过,我不知道这样做的最佳实践,也不知道PHPUnit是否允许这样做.

I'd expect that I'd have to create some sort of object as part of the test. Though, I've no idea the best practice for this or if PHPUnit allows for this.

推荐答案

抽象类的单元测试不一定意味着要测试接口,因为抽象类可以具有具体的方法,并且可以测试具体的方法.

Unit testing of abstract classes doesn't necessary mean testing the interface, as abstract classes can have concrete methods, and this concrete methods can be tested.

在编写一些库代码时,具有某些期望在应用程序层中扩展的基类并不少见.而且,如果要确保已测试库代码,则需要使用方法来抽象类的具体方法.

It is not so uncommon, when writing some library code, to have certain base class that you expect to extend in your application layer. And if you want to make sure that library code is tested, you need means to UT the concrete methods of abstract classes.

我个人使用PHPUnit,它具有所谓的存根和模拟对象,以帮助您测试这种事情.

Personally, I use PHPUnit, and it has so called stubs and mock objects to help you testing this kind of things.

直接从 PHPUnit手册:

abstract class AbstractClass
{
    public function concreteMethod()
    {
        return $this->abstractMethod();
    }

    public abstract function abstractMethod();
}

class AbstractClassTest extends PHPUnit_Framework_TestCase
{
    public function testConcreteMethod()
    {
        $stub = $this->getMockForAbstractClass('AbstractClass');
        $stub->expects($this->any())
             ->method('abstractMethod')
             ->will($this->returnValue(TRUE));

        $this->assertTrue($stub->concreteMethod());
    }
}

模拟对象为您提供了几件事:

Mock object give you several things:

  • 您不需要具有抽象类的具体实现,而可以使用存根代替
  • 您可以调用具体方法并断言它们正确执行
  • 如果具体方法依赖于未实现(抽象)的方法,则可以使用will()PHPUnit方法对返回值进行存根

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

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