Skip to content

Can I use seperate database for using phpunit for integration testing in crons?

Sometimes I want to ensure that for some cases that records are written correcntly upon database mostly in cron for bulk actions that read records from one table and written into another table for example this cron job:

namespace PcmagasPhpUnitLearnModuleCron;

use PcmagasPhpUnitLearnModuleModelFactoriesCustomerEmailCollectionFactory;
use MagentoFrameworkAppConfigScopeConfigInterface;

class SetCustomersToDefaultCustomerGroup
{
    private CollectionFactory $factory;

    private ScopeConfigInterface $scopeConfig;

    public function __construct(
        CollectionFactory $factory,
        ScopeConfigInterface $scopeConfig
    ) {
        $this->factory = $factory;
        $this->scopeConfig=$scopeConfig;
    }

   
    public function execute()
    {
        /**
         * @var $collection MageGuideCustomerEmailsModelResourceModelCustomerEmailCollection
         */
        $collection = $this->factory->create();
        $table = $collection->getMainTable();
        /**
         * @var $resource MagentoFrameworkDBAdapterPdoMysqlInterceptor
         */
        $resource = $collection->getConnection();

        // @todo use magento's config.
        $default_customer_group=(int)$this->scopeConfig->getValue("default_group_id/myplugin/default_group_id");

        /**
         * Emails where the group id will be changed
         * @var MagentoFrameworkDBSelect
         */
        $select = $resource->select()
            ->from($table,'emails')
            ->join('customer_entity',$table.".email=customer_entity.email")
            ->where("customer_entity.group_id <> $table.customer_group_id")
            ->columns([$table.'.email']);

        $queryResults = $resource->fetchAll($select);


        try {
            $resource->beginTransaction();
            foreach($queryResults as $email){
                if(empty($emails)){
                    continue ;
                }
                $resource->update(
                    'customer_entity',
                    ['group_id'=>$default_customer_group],
                    [
                        'email '=>$email
                    ]
                );
            }
            $resource->commit();
        } catch (Exception $e) {
            $resource->rollBack();
        }
    }
}

In my case I have 2 tables:

  1. One that has the email list
  2. The customer_entity table

And I want to write a test that checks that emails will be written correctly. Usually upon php projects I mock everything EXCEPT the database, especially in laravel. Usually what I do is either at phpunit.xml or at .env.testing I set the tersting database credentials that are used instead ones from the normal installation.

So is there an approach where I can configure a seperate – test only database at magento. And setup the nessesary schema with nessesary modules only (disabling the ones not needed for testing)?