samedi 4 août 2018

Testing overriden trait method execution

I have situation like this. I have some 3rd party trait (I don't want to test) and I have my trait that uses this trait and in some case runs 3rd party trait method (in below example I always run it).

When I have code like this:

use Mockery;
use PHPUnit\Framework\TestCase;

class SampleTest extends TestCase
{
    /** @test */
    public function it_runs_parent_method_alternative()
    {
        $class  = Mockery::mock(B::class)->makePartial();

        $class->shouldReceive('fooX')->once();

        $this->assertSame('bar', $class->foo());
    }

    protected function tearDown()
    {
        Mockery::close();
    }
}

trait X {
    function foo() {
        $this->something->complex3rdpartyStuff();
    }
}

trait Y2 {

    function foo() {
        $this->fooX();
        return 'bar';
    }
}

class B {
    use Y2, X {
        Y2::foo insteadof X;
        X::foo as fooX;
    }
}

it will work fine however I don't want code to be organized like this. In above code in class I use both traits but in code I want to test in fact trait uses other trait as mentioned at the beginning.

However when I have code like this:

<?php

use Mockery;
use PHPUnit\Framework\TestCase;

class SampleTest extends TestCase
{
    /** @test */
    public function it_runs_parent_method()
    {
        $class  = Mockery::mock(A::class)->makePartial();

        $class->shouldReceive('fooX')->once();

        $this->assertSame('bar', $class->foo());
    }

    protected function tearDown()
    {
        Mockery::close();
    }
}

trait X {
    function foo() {
        $this->something->complex3rdpartyStuff();
    }
}

trait Y {
    use X {
        foo as fooX;
    }

    function foo() {
        $this->fooX();
        return 'bar';
    }
}

class A {
    use Y;
}

I'm getting:

undefined property $something

so it seems Mockery is not mocking in this case X::foo method any more. Is there are way to make possible to write such tests with code organized like this?

Aucun commentaire:

Enregistrer un commentaire