Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing Phpunit、依赖注入、测试存根:注入mock还是匿名对象?_Unit Testing_Mocking_Phpunit - Fatal编程技术网

Unit testing Phpunit、依赖注入、测试存根:注入mock还是匿名对象?

Unit testing Phpunit、依赖注入、测试存根:注入mock还是匿名对象?,unit-testing,mocking,phpunit,Unit Testing,Mocking,Phpunit,我有点怀疑该注射什么。鉴于此代码: class A { public function getSomething() { return 'something'; } } class TestMe { /** * @var A */ private $a; public function __construct($a) { $this->a = $a; } pub

我有点怀疑该注射什么。鉴于此代码:

class A
{
    public function getSomething()
    {
        return 'something';
    }
}

class TestMe
{
    /**
     * @var A
     */
    private $a;

    public function __construct($a)
    {
        $this->a = $a;
    }

    public function greetings()
    {
        return 'Hello, '.$this->a->getSomething();
    }
}
我的测试A:

function testA()
{
    $a = new class() {
        public function getSomething()
        {
            return 'aAnonimus';
        }
    };

    $sut = new TestMe($a);

    $this->assertEquals($sut->greetings(), 'Hello, aAnonimus');
}
testB,相同,但带有模拟:

function testA()
{
    $a = $this->createMock(A::class);
    $a->method('getSomething')->willReturn('bMockery');

    $sut = new TestMe($a);

    $this->assertEquals($sut->greetings(), 'Hello, bMockery');
}
在第一个测试中,我只注入一个普通对象。 但第二种更像Phpunit的方式:使用模拟对象


问题是,在很长一段时间内,哪一方获胜?我发现第一种方法更方便,对于第二种测试,您必须知道依赖项的类名(否则您无法创建模拟)

从长远来看,第二种方法更好,因为最好在构造函数中包含类型提示,这将不允许您提供简单的对象。
此外,当我们讨论单元测试时,您应该测试某个类,而不依赖第三方库或其他服务逻辑。所以最好的方法是对测试类中的所有服务使用mock

,任何人“知道依赖项的类名”有什么不对?因为如果它发生变化,测试也应该如此。嗯。。。另一个视图如何:您需要更改某些依赖项->您在测试用例中设置它->您在源代码中更改它?我的意思是2点:a)在类中通常不使用随机依赖项,是吗?你需要smth的具体,可预期的和可靠的排序;b) 是的,源代码和测试代码之间存在某种关联,它们相互遵循(没有人想要不相关的测试)。从技术上考虑类型暗示的依赖关系——无论如何,您都需要扩展匿名类,即===“知道类名”。从长远来看,phpunit方法无疑是最好的选择。您可以向它添加
expects
,以确保它确实被调用。您可以向它添加
,以确保使用正确的变量调用它。如果函数被多次调用,可以使用
willReturnOnConsecutiveCalls
使其返回不同的值。