aspiresuvedi's avatar

Tests file uploads using phpunit and mockery

I am newbie to phpunit tests. I need to write tests to a service class Uploader which has following functions

public function saveClientDocument($client, $documents, $inputs)
    {
        foreach ($documents as $document) {
            $pathName = $this->generatePathName($document->getClientOriginalName());
            if ($this->moveDocument($document, $pathName)) {
                $data = [
                    'original_name' => $document->getClientOriginalName(),
                    'path_name'     => $pathName,
                    'document_type' => $inputs['document_type'],
                    'uploader'      => $this->auth->user()->id
                ];
                $this->saveDocument($client, $data);
            }
        }
        $this->logger->info(sprintf('%d documents uploaded for client %d', count($documents), $client->id));
        return true;
    }

    protected function moveDocument($document, $pathName)
    {
        try {
            $document->move($this->uploadPath, $pathName);
            return true;
        } catch (Exception $e) {
            $this->logger->error('Error on uploading document ', ['message' => $e->getMessage()]);
            return false;
        }
    }

    protected function saveDocument($client, $data)
    {
        if (!$this->documentRepository->save($client, $data)) {
            $this->logger->error('Document is not saved.');
            return false;
        }
        return true;
    }

    protected function generatePathName($name)
    {
        return md5(microtime() . $name);
    }

I need to write tests for public function saveClientDocument()

I am confused about calling the protected functions which is called inside the public functions and also confused about using mockery of file uploads and logger ? Any help to write tests for the public function would really be appreciated. :)

0 likes
0 replies

Please or to participate in this conversation.