K
K
kaxa32012018-12-27 17:14:52
PHPUnit
kaxa3201, 2018-12-27 17:14:52

How to write phpunit api tests in laravel?

There is a method in the controller, please tell me how to write a test for it, I can’t understand where to start and what should happen in the end, please explain using my example.

public function addResource(Request $request)
    {
        $url = $request->input('url');
        $result = $this->service->saveContent($url);

        if ($result !== null) {
            return response()->json(['status' => 'ok', 'message' => 'Ресурс добавлен', 'data' => $result]);
        }

        return response()->json(['status' => 'error', 'message' => 'Ошибка', 'data' => ['url' => $url]]);
    }

But where I started, and then a stupor
public function testBasicExample()
    {
        $response = $this->json('POST', '/api/resource', ['name' => 'saveContent']);
        $service = $this->createMock(Request::class);
        
        $contentController = new ContentController($service);
       
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaliy Orlov, 2018-12-27
@orlov0562

1) You need to test requests to api, in this case you just check the response like this

$response = $this->post('/api/upload');
        $response
            ->assertStatus(200)
            ->assertExactJson([
                'code' => 200,
                'output' => [],
            ]);
        ;

See example
here 2) You also need to check addResourse, it's more difficult there, you need to create a mock request and add only the necessary parameters there, you have this url. You need to check different urls: empty, incorrect, correct, etc.
After the call, we also check the Json assert, and also whether the file is saved or not.
See examples here:
- uploading files
- working with Request
Of course, there are more of. Help , but I think you've already looked there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question