I've started with writing and figure out unit testing in Magento 2. I want to write a test case for getting an order by the increment id.
This is my function which I want to write a test for:
/**
* @param $incrementId
* @return false|OrderInterface
*/
public function getOrderByIncrementId($incrementId)
{
$searchCriteria = $this->searchCriteriaBuilder->addFilter(
OrderInterface::INCREMENT_ID,
$incrementId
)->create();
$result = $this->orderRepo->getList($searchCriteria);
if (empty($result->getItems())) {
throw new NoSuchEntityException(__('No such order.'));
}
$orders = $result->getItems();
return reset($orders);
}
I am using the Magento\Sales\Api\OrderRepositoryInterface
and the Magento\Framework\Api\SearchCriteriaBuilder
for it.
Now I wrote the following test, created mocks for the classes, but I can't get an actual object for the $searchCriteria
.
This is my setUp function:
protected function setUp(): void
{
$this->orderInterfaceMock = $this->getMockBuilder(OrderInterface::class)
->disableOriginalConstructor()
->getMock();
$this->orderSearchResultInterface = $this->getMockBuilder(OrderSearchResultInterface::class)
->disableOriginalConstructor()
->getMockForAbstractClass();
$this->orderRepositoryMock = $this->getMockBuilder(OrderRepositoryInterface::class)
->disableOriginalConstructor()
->setMethods(['getList'])
->getMockForAbstractClass();
$this->searchCriteriaBuilderMock = $this->getMockBuilder(SearchCriteriaBuilder::class)
->disableOriginalConstructor()
->setMethods(['create','addFilter'])
->getMock();
$this->templateContextMock = $this->getMockBuilder(Context::class)
->disableOriginalConstructor()
->getMock();
$this->checkoutSessionMock = $this->getMockBuilder(CheckoutSession::class)
->disableOriginalConstructor()
->getMock();
$this->orderConfigMock = $this->getMockBuilder(Config::class)
->disableOriginalConstructor()
->getMock();
$this->httpContextMock = $this->getMockBuilder(HttpContext::class)
->disableOriginalConstructor()
->getMock();
$this->object = new Success(
$this->orderRepositoryMock,
$this->searchCriteriaBuilderMock,
$this->templateContextMock,
$this->checkoutSessionMock,
$this->orderConfigMock,
$this->httpContextMock,
[]
);
}
And this my test case
/**
* @param $incrementId
* @dataProvider getIncrementIdProvider
*/
public function testGetOrderByIncrementId($incrementId)
{
$result = $this->object->getOrderByIncrementId($incrementId);
$this->assertInstanceOf(OrderInterface::class, $result);
}
I am getting this error:
Error : Call to a member function create() on null
I am not sure if it's ok to just create a new object from the real Success class. I saw it somewhere else with the object manager, but as I know, this helper is only for integration tests. I can't figure it out and would appreciate your input. I am also not sure about the getList function. I added it to the OrderRepository, that should be enough, right?