DEV Community

Php Profi
Php Profi

Posted on • Originally published at brandonsavage.net on

1

Не пишите бесполезные unit-тесты

PhpUnit

На днях я наткнулся на следующий код в проекте:

class Users
{
    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function getAllUsers()
    {
        $stmt = $this->pdo->prepare('SELECT * FROM users');
        return $stmt->fetchAll();
    }
}
Enter fullscreen mode Exit fullscreen mode

 

И был вот такой тест для проверки этого кода:

class UserTest extends TestCase
{
    public function testGetAllUsers()
    {
        $pdo = m::mock(PDO::class);
        $stmt = m::mock(PDOStatement::class);

        $pdo->shouldReceive(‘prepare’)->andReturn($stmt);
        $pdoStmt->shouldReceive(‘fetchAll’)->andReturn($userArray);

        $users = new Users($pdo);
        $result = $users->getAllUsers();

        $this->assertEquals($userArray, $users);
    }
}
Enter fullscreen mode Exit fullscreen mode

Обратите внимание, что я опустил остальную часть класса User, а также массив пользователей, который возвращается в тесте.

Этот тест на самом деле даёт нам 100%-ое покрытие кода в методе getAllUsers(). Но, к сожалению, для любой практической цели, этот тест полностью бесполезен.


Читать далее: http://phpprofi.ru/blogs/post/94


En: https://www.brandonsavage.net/dont-write-useless-unit-tests/

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay