How to Write Database Integration Tests in Magento 2

databaseintegration-testmagento2testing

I know how to test methods that return some values – that is basic unit testing, but what if I want to test methods that enter values to database. I have found this post, that says integration test are right for that?

Also I have found this blog post. Where is example how to write integration tests, to test category and product creation. It uses $this->dispatch() method to get page content from url.

My question is: I have not fount any examples how to write integration tests, which would test database entries that are not displayed in front-end or back-end. Can anyone please post any example codes (I am beginner at Test Driven Development)?

Background: I am trying to write module, that uses previously stored data from database (functions ran by cron are using the data).

Best Answer

In integration tests you may use the object manager to work with Magento objects, like repositories.

For example:

use Magento\Framework\App\ObjectManager;
use Magento\Sales\Model\OrderRepository;

class YourTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var OrderRepository
     */
    private $orderRepository;
    /**
     * @var ObjectManager
     */
    private $objectManager;


    protected function setUp()
    {
        $this->objectManager = ObjectManager::getInstance();
        $this->orderRepository = $this->objectManager->create(OrderRepository::class);
    }

    public function testSomething()
    {
        // do stuff

        $orders = $this->orderRepository->getList( ... );

        // make assertions
    }
}
Related Topic