简体   繁体   English

如何测试使用静态工厂的方法?

[英]How to test a method that's using a static factory?

Now that..I'm using IoC container and DI with all my projects, I would like to learn how I should have tested my codes when I was using a static factory (I didn't do any unit testing back then). 现在,我在所有项目中都使用了IoC容器和DI,我想学习在使用静态工厂时应该如何测试我的代码(当时我没有进行任何单元测试)。 Let's say I have the following code snippet. 假设我有以下代码段。

class TestFactory {

    public static function create($something) {
        switch($something) {
            case 1:
                return Dummy;
                break;
        }
    }

}

class Client {

    public function __construct() {

        $this->aClass = TestFactory::create(1);

    }

}

If I want to unit test Client class, how do I do that without using DI or IoC container? 如果我想对Client类进行单元测试,如何在不使用DI或IoC容器的情况下做到这一点?

2 ways: 2种方式:

  1. Make sure you TestFactory is running fine with the test framework and just test Client with TestFactory running. 确保您的TestFactory在测试框架中运行良好,并且仅在运行TestFactory的情况下测试Client。 (recommended) (推荐的)

  2. Inherit Client class and have __construct() return a dummy object if you must separate the Client as a separate test case. 如果必须将Client作为单独的测试用例进行分离,则继承Client类并让__construct()返回一个虚拟对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM