1

I have the problem with writing unit tests. It's my first attempt and I don't know how can I test a couple of cases in my code.

It's action in my controller:

    public function execute()
    {
            $params = $this->getRequest()->getParams();
            $redirect = $this->_redirect('*/*');
            if ($params) {
                $redirect->setMetadata('params', true);
                try {
                    $customerId = $this->_customerHelper->getCustomer()->getId();
                    $this->_reportModel->getCollection()
                        ->addFieldToFilter('customer_id', $customerId)
                        ->addFieldToFilter('type', Entity::CUSTOMER_PREASEASON)
                        ->getFirstItem()
                        ->delete();

                    $this->_reportModel->setData([
                        'customer_id' => $customerId,
                        'type' => Entity::CUSTOMER_PREASEASON,
                        'extra_data' => serialize([
                            'year' => $params['year'],
                            'season' => $params['season']
                        ]),
                    ])->save();
                    $this->messageManager->addSuccessMessage('You request will be processed');
                    return $redirect;
                } catch (Exception $exception) {
                    $this->messageManager->addErrorMessage('Some occurred error');
                }
            }
            $redirect->setMetadata('params', false);
            return $redirect;
}

I have to test such cases:

   $this->_reportModel->getCollection()
                        ->addFieldToFilter('customer_id', $customerId)
                        ->addFieldToFilter('type', Entity::CUSTOMER_PREASEASON)
                        ->getFirstItem()
                        ->delete();

And

$this->_reportModel->setData([
                    'customer_id' => $customerId,
                    'type' => Entity::CUSTOMER_PREASEASON,
                    'extra_data' => serialize([
                        'year' => $params['year'],
                        'season' => $params['season']
                    ]),
                ])->save();

How can I do this? should I initialize $this->_reportModel as real model and save it? Or create Mock ($this->_reportModelMock) and set condition for it and do like:

$this->_reportCollectionMock->expects($this->once())
            ->method('getFirstItem')
            ->willReturn($this->_reportModelMock);

Maybe I'm wrong and it's not the right way. I will be very grateful if you help me ))) also I will grateful for an example similar to my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.