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/

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay