Skip to content

Unit Test Case for updateOrderStatus($orderId)

I am new in writing unit testing in Magento 2. I want to write a test case for getting an order by the order_id.

Below is my model function:

public function updateOrderStatus($orderId)
    {    
       if ($orderId) {
            $order = $this->orderRepository->get($orderId);
            $order->setState(MagentoSalesModelOrder::STATE_PROCESSING);
            $order->setStatus(self::SENT_TO_WAREHOUSE);
            $comment = "Order Status Changed to Sent to Warehouse";
            try {
                $order->addStatusToHistory(
                    self::SENT_TO_WAREHOUSE,
                    $comment
                );
                $this->orderRepository->save($order);
} catch (Exception $e) {
            }
}

I have used MagentoSalesApiOrderRepositoryInterface $orderRepository repository,

Below is my test case functions:

use MagentoSalesApiDataOrderInterface;
use MagentoSalesApiOrderRepositoryInterface;

protected function setup(): void
    {
           $this->_orderRepositoryInterface = $this->getMockBuilder(OrderRepositoryInterface::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->orderMock = $this->getMockBuilder(OrderInterface::class)
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

          $this->objectManager = new MagentoFrameworkTestFrameworkUnitHelperObjectManager($this);

          $this->model = $this->objectManager->getObject(
            ModelClassName::class,
            [
                'helper' => $this->helper,
                'json' => $this->json,
                'orderRepositoryInterface' => $this->_orderRepositoryInterface,
                'orderInterface' => $this->_orderInterface,
                'orderFactory' => $this->orderFactory
            ]
        );
}

public function testUpdateOrderStatus()
{
    $orderID = '57956';
    $this->_orderRepositoryInterface->expects($this->once())
        ->method('get')
        ->willReturn($this->orderMock);

    $this->orderMock->expects($this->once())
        ->method('setState')->with("processing")
        ->willReturnSelf();

    $this->orderMock->expects($this->once())
        ->method('setStatus')->with("sent_to_warehouse")
        ->willReturnSelf();

    $this->_orderRepositoryInterface->expects($this->once())
        ->method('save')
        ->with($this->orderMock)
        ->willReturnSelf();

    $this->assertEquals(true, $this->model->updateOrderStatus($orderID));

$this->model is my original model class for which i am writing Test Unit.
I am receiving error like below :

Error: Call to a member function setState() on null

As i said i am new in writing unit tests, so if anyone can get idea from above code then it will helpful for me.

Thanks in advance.