DEV Community

Cover image for My practices of writing Unit-tests
alexdodonov
alexdodonov

Posted on

My practices of writing Unit-tests

For my whole life I have written about 2700 unit tests. For example here are about 1300 unit-tests and code coverage is almost 100%.

I am not the most skillfull person but I have some tricks wich helpms to write more tests and easier maintain them. Hope they will be usefull for you.

Examples will be written for PHPUnit and PHP but you can implement all advices for any other unit-testing framework for any language you want.

Strict structure for all unit-tests

All my tests have absolutely the same structure (excepti for tests wich test exception )) ) and it looks like this:

// setup
here we have setup commands

// test body
here we call testing method

// assertions
here we validate the result
Enter fullscreen mode Exit fullscreen mode

And here is some real life example:

/**
 * Testing method addPostRoute
 */
public function testAddPostRoute(): void
{
    // setup
    $router = $this->getRouter();
    $route = 'route';
    RouterUnitTestUtils::setRequestMethod('POST');

    // test body
    $router->addPostRoute($route, $this, 'actionRoute');

    // assertions
    $this->assertEquals(1, $router->callRoute($route));
}
Enter fullscreen mode Exit fullscreen mode

Here strict structure of unit-test will help you easyly understand what is happening. And also prevents your tests from becoming a mess.

In some cases unit-test's structure can be a little different, but it consists of the same three parts: setup, test body and assertions. Just look at hte example:

/**
 * Testing exception while getting existing file
 */
public function testExceptionWhileGettingFileContent(): void
{
    // assertions
    $this->expectException(\Exception::class);
    $this->expectExceptionCode(- 1);
    $this->expectExceptionMessage('File unexisting does not exists');

    // setup
    InMemory::clearFs();

    // test body
    Layer::existingFileGetContents('unexisting');
}
Enter fullscreen mode Exit fullscreen mode

This trick can be used for Selenium tests also, but it can be modified like this:

// prepare test data

// move our web app to the necessary state

// test body

// assertions
Enter fullscreen mode Exit fullscreen mode

Here "move our web app to the necessary state" are steps wich need to be perfomed before testing functionality. For example you want to display data grid. So your selenium test will look like this (in pseudo code):

// prepare test data
create records for the grid
create testing user
grant permissions for him

// move our web app to the necessary state
login with the created user
open menu

// test body
click on the link in the menu to open testing grid

// assertions
verify that all created records are displayed
Enter fullscreen mode Exit fullscreen mode

That's all for now. Hope this article will be usefull for you. If so - please press "STAR" for my project.

Top comments (0)