Douglasdc3 / laravel-kong

A fluent api wrapper around Kong's API manger designed for Laravel.
MIT License
25 stars 13 forks source link

Mocking classes #20

Open EntonoX opened 3 years ago

EntonoX commented 3 years ago

For our authentication service i need to write some tests with phpunit. I'm using Lumen framework and having problems to mock classes.

What i'm trying;

$kongHttpClient = Mockery::mock(\DouglasDC3\Kong\Http\HttpClient::class);

$kongHttpClient->shouldReceive('get')->once()->andReturn(json_encode([]));

$this->app->instance(\DouglasDC3\Kong\Http\HttpClient::class, $kongHttpClient);

This way i'm trying to mock a Kong reply, so i can test my user creation / JWT generation to the point that Kong endpoints are called.

But is seems this mock isnt'getting called at all. Any other ideas on how to try to mock?

Douglasdc3 commented 3 years ago

@EntonoX Can you test this in the latest release (v1.2.1) I changed the service provided to allow swapping the HttpClient instance

The fix

EntonoX commented 3 years ago

I did a small test with the provided code in my first post, but it still seems to get the normal HttpClient class.

I also tried to add

 $this->app->bind(\DouglasDC3\Kong\Http\HttpClient::class, function() use ($kongHttpClient) {
           return $kongHttpClient;
        });

after the $this->app->instance call, but that don't seem to work either.

Did you test replacing the HttpClient ?

EDIT: maybe its due to me using Lumen instead of Laravel

Douglasdc3 commented 3 years ago

I tested this in Laravel (8) with the following test code and got green test could you test this?

        $mockClient = \Mockery::mock(HttpClient::class);
        $mockClient->shouldReceive('get')->andReturn([
            'version' => 'test-version',
            'hostname' => 'test-hostname',
        ]);

        $this->swap(HttpClient::class, $mockClient);

        $kong = app(Kong::class);
        $info = $kong->info();

        $this->assertEquals('test-version', $info->version);
        $this->assertEquals('test-hostname', $info->hostname);

Haven't tested this in Lumen let met know what the above test case returns

EntonoX commented 3 years ago

I'm going to test this further next week, little bit of a thight work shedule. i'll keep you updated