User Tools

Site Tools


programmieren:testing:unittest

Unit Tests

Unit tests, as the name implies are tests that are made for certain units of code. Here we usually (if possible) do one test class per actual code class, and one or more test methods per actual code method.

Unit testing is useful for keeping an eye on the code when changes to the code are made. It helps with identifying problems with failed tests, caused by code changes that maybe weren't apperant before.

Unit tests usually are made for utilising the certain functionality its supposed to test, and then checking if it aligns with what you'd expect the functionality to do.

For example the function gets a list of entries of a database table. You check the fixtures and expect the entries in the fixture to be the result of the function. You then call the function and check the actual result against the expected result.

Example:

    /**
     * Tests the upsert method when updating an existing tag record
     *
     * @return void
     * @covers ::__construct
     * @covers ::upsert
     * @covers ::upsertRecord
     */
    public function testUpsertUpdate(): void
    {
        $tagUuid = '586daef3-9c8d-352b-9cd9-005e12c563ef';
        $tagName = 'upgrade';
        $accountId = 1;
 
        $cloudSigmaTag = new Tag(
            $tagUuid,
            $tagName,
            $accountId,
        );
 
        /** @var AppTag $tagsCount */
        $tagsCount = $this->tagsTable->find()
            ->where(['uuid' => $tagUuid])
            ->count();
 
        self::assertSame(1, $tagsCount);
 
        $this->tagsRepository->upsert($cloudSigmaTag);
 
        /** @var AppTag $appTag */
        $appTag = $this->tagsTable->find()
            ->where(['uuid' => $tagUuid])
            ->first();
 
        self::assertSame($accountId, $appTag->account_id);
        self::assertSame($tagName, $appTag->name);
    }

This upserts a tag whose uuid already exists, so the tag gets its content updated with the new data. The changed data is asserted afterwards because that is the expected action.

programmieren/testing/unittest.txt · Last modified: by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki