测试抽象类 [英] Testing Abstract Classes

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

问题描述

如何使用 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.

在编写一些库代码时,您希望在应用程序层中扩展某些基类并不少见.而如果要确保库代码经过测试,则需要对抽象类的具体方法进行 UT 测试.

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 对象给你几样东西:

Mock object give you several things:

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

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

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