简体   繁体   中英

How to test a controller that communicate with a microservice?

I have the next scenario: I have to write some unit testings for controllers. In the controllers i have all types of CRUD actions. The problem is that in actions of post/patch/delete my api is communicating with a web service where i pass some data. The communication is done with guzzle.

Question: How to avoid the communication when i call a route? Is there other possibility to test the hall controller?

I assume that your microservice is a class which is registered in the Laravel's service container. As far as I know, you can't mock classes outside the container in Laravel.

So, In case you're not doing that, register the service in the container in AppServiceProvider class. And get the microservice from the container in the controller See here for details .

In your unit test, you can make a mock object of your microservice according to your needs and inject it in the container (replacing the real one). for eg.

$this->instance(MyMicroService::class, Mockery::mock(MyMicroService::class, function ($mock) {
    // here you tell the mock object which method will be called and what to return and how many times it will be called. it's totally customizable.
    $mock->shouldReceive('contactRemoteServer')->once()->andReturnTrue();
}));

and it's easier if you use the mock method in your testcase class, but it does the same thing:

$this->mock(MyMicroService::class, function ($mock) {
    $mock->shouldReceive('contactRemoteServer')->once()->andReturnTrue();
});

see the docs for more examples.

NB: In case you don't know, A mock class is a class made especially for the test so it doesn't affect the results and to be controllable in accordance to the test needs.

For example if you want to have a case where your microservice will throw an exception and you want to test the controller's response for that you will have to create a mock class for each unit test.

Create a sample class with the same functionality but I have one question if you are creating unit tests and you don't want to make the guzzle work so what will you test.

Please read the documentation carefully you will get the option.

In my suggestion, you can use mocking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM