vendredi 30 octobre 2015

How Unit Test a PHP Command Class

I'm trying to unit test a PHP Application. I'm also new to Unit Testing and maybe this shouldn't be one of my first Unit Test Cases, but still I need to get this done, so...

I have a PHP command Class with 2 methods and a __construct(). the execute method loops through an array (obtained by a DBAL read) and calls executeSingleRow, which reads the DB, makes some consideration and, just if a few conditions are satisfied, calls the execute method of another command.

I just can't figure out how a good Unit Test can be done here, or how should I modify the code.

Here are my Class methods:

public function __construct(
    $registry,
    $firstTableRepository,
    $secondTableRepository,
    AnotherCommand $anotherCommand,
    JobLogRepository $logger = null
)
{
    $this->registry = $registry;
    $this->stagione = $this->registry->get('stagione');
    $this->firstTableRepository = $firstTableRepository;
    $this->secondTableRepository = $secondTableRepository;
    $this->anotherCommand= $anotherCommand;
    $this->logger = $logger;
    $this->error = false;
}

public function execute($toReplace, $replacer, $selected)
{
    foreach ($selected as $selectedRow) {
        firstTableID = $selectedRow['ID'];
        $this->executeSingleRow($toReplace, $replacer, firstTableID);
    }
    if ($this->error) {
        $this->keyException(null, 'Procedura terminata con errori');
    }
}


public function executeSingleRow($toReplace, $replacer, firstTableID)
{
    if ($toReplace == $replacer) {
        $this->error = true;
    } else {
        $firstTableRow = $this->firstTableRepository->readByID(firstTableID);
        if (!empty($firstTableRow)) {
            $CODE = $firstTableRow['CODE'];
            $newCODE = str_replace($toReplace, $replacer, $CODE);
            if ($newCODE != $CODE) {
                $articoloNuovo = $this->secondTableRepository->readByCode($newCODE);
                if ($articoloNuovo) {
                    $secondTableIDNuovo = $articoloNuovo['secondTableID'];
                    try {
                        $this->anotherCommand->setJobLog($this->jobLog);
                        $this->anotherCommand->execute($secondTableIDNuovo, 'G', firstTableID);
                        return;
                    } catch (\Exception $e) {
                        $this->error = true;
                    }
                } else {
                    $this->error = true;
                }
            } else {
                $this->error = true;
            }
        } else {
            $this->error = true;
        }
    }
}

Thanks a lot for being so kind to read and answer if possible!

Aucun commentaire:

Enregistrer un commentaire