AspectMock icon indicating copy to clipboard operation
AspectMock copied to clipboard

How to return values from mocked method using test::spec

Open bartdorsey opened this issue 6 years ago • 4 comments

Is it possible to return fake values from mocked methods using an object created with test::spec ? I've tried this and it never seems to call my fake method:

$fakeValue = '1';
$mock = test::spec('FakeClass', [
    'fakeMethod' => function () {
         return $fakeValue;
    }
])->construct();

Then when I call $mock->fakeMethod() it's not returning my fakeValue;

Is this just supported or am I doing something wrong?

bartdorsey avatar Feb 23 '18 14:02 bartdorsey

your $fakeValue is out of scope.

    'fakeMethod' => function () use ($fakeValue) {
         return $fakeValue;
    }

adrian-enspired avatar Mar 06 '18 05:03 adrian-enspired

Doh. I'll have to try this then, thanks.

bartdorsey avatar Mar 06 '18 06:03 bartdorsey

I'm still having problems with this. Here's my latest example.

   $mockDB = test::spec('DB', [
        'queryRow' => function () {
             codecept_debug('Inside Fake Function');
             return 1;
         }
   ])->construct();
   codecept_debug($mockDB->queryRow());

This should return a 1 and codecept_debug twice.

It only logs once and prints this:

AspectMock\Proxy\Anything Object
  (
      [className:AspectMock\Proxy\Anything:private] => DB
  )

I've also tried putting the array of methods to override inside the construct() call. It does the same thing.

bartdorsey avatar Mar 27 '18 22:03 bartdorsey

public function testAspectMock()
        {
            $mockThing = test::spec('FakeClass', [
                'fakeMethod' => function () {
                    return "Hello World";
                }
            ])->construct();
            $this->assertEquals($mockThing->fakeMethod(), "Hello World");
        }

Here's a test I wrote in my codeception unit test that fails with this:

Failed asserting that 'Hello World' matches expected AspectMock\Proxy\Anything Object &000000006b16ca0d000055bfa042f94a (
    'className' => 'FakeClass'
).

bartdorsey avatar Mar 27 '18 22:03 bartdorsey