phpstan / phpstan-phpunit

PHPUnit extensions and rules for PHPStan
MIT License
468 stars 46 forks source link

Raise an error in PHPunit when calling createMock where createStub is enough #210

Open ChinaskiJr opened 2 months ago

ChinaskiJr commented 2 months ago

Feature request

Hi !

In order to enforce and clarify the usage of test doubles for everyone, I would like to know if you think it would be beneficial to implement a rule that raises an error when a mock is created without any assertions on being called (essentially making it a stub).

This rule would only be about using the correct terminology for test doubles. It should help to better understand what is going on in our test, and what is our intention.

https://docs.phpunit.de/en/10.5/test-doubles.html

In example :

<?php
// This will raise an error : 
public function testSomething(): void 
{
    $stub = $this->createMock(Foo::class);
    $stub->method('foo')->willReturn('bar');

    self::assertSame('bar', $stub->foo());
}

// This won't raise an error : 
public function testSomething(): void 
{
    $stub = $this->createStub(Foo::class);
    $stub->method('foo')->willReturn('bar');

    self::assertSame('bar', $stub->foo());
}

// This won't raise an error : 
public function testSomething(): void 
{
    $mock = $this->createMock(Foo::class);
    $mock->expects($this->once())->method('foo')->willReturn('bar');

    self::assertSame('bar', $mock->foo());
}

I can try to make a PR for this, but before working on it, I prefer to ask if you think it would be a good improvement.