5

Str::random()テストしたいクラスがあります。

しかしStr::shouldReceive('random')、テストで使用すると、メソッド shouldReceive が存在しないという BadMethodCallException が発生します。

また、クラスを直接モックして IOC にバインドしようとしましたが、元のクラスを実行し続け、モックに設定した戻り値ではなく、ランダムな文字列を生成します。

    $stringHelper = Mockery::mock('Illuminate\Support\Str');
    $this->app->instance('Illuminate\Support\Str', $stringHelper);
    //$this->app->instance('Str', $stringHelper);

    $stringHelper->shouldReceive('random')->once()->andReturn('some password');
    //Str::shouldReceive('random')->once()->andReturn('some password');
4

3 に答える 3

0

この方法で Illuminate\Support\Str をモックアウトすることはできません ( mockery docsを参照してください。これが私がテストする方法です。

ランダムな文字列を生成しようとするクラスでは、ランダムな文字列を生成するメソッドを作成し、テストでそのメソッドをオーバーライドできます (コードは実際にはテストされていません)。

    // class under test
    class Foo {
        public function __construct($otherClass) {
            $this->otherClass = $otherClass;
        }

        public function doSomethingWithRandomString() {
            $random = $this->getRandomString();
            $this->otherClass->useRandomString($random);
        }

        protected function getRandomString() {
            return \Illuminate\Support\Str::random();
        }
    }

    // test file
    class FooTest {
        protected function fakeFooWithOtherClass() {
            $fakeOtherClass = Mockery::mock('OtherClass');
            $fakeFoo = new FakeFoo($fakeOtherClass);
            return array($fakeFoo, $fakeOtherClass);
        }

        function test_doSomethingWithRandomString_callsGetRandomString() {
             list($foo) = $this->fakeFooWithOtherClass();
             $foo->doSomethingWithRandomString();

             $this->assertEquals(1, $foo->getRandomStringCallCount);
        }

        function test_doSomethingWithRandomString_callsUseRandomStringOnOtherClassWithResultOfGetRandomString() {
            list($foo, $otherClass) = $this->fakeFooWithOtherClass();

            $otherClass->shouldReceive('useRandomString')->once()->with('fake random');
            $foo->doSomethingWithRandomString();
        }
    }
    class FakeFoo extends Foo {
        public $getRandomStringCallCount = 0;
        protected function getRandomString() {
            $this->getRandomStringCallCount ++;
            return 'fake random';
        }
    }
于 2014-06-29T16:40:43.957 に答える