maks3w/phpunit-methods-trait
PHP trait exposing PHPUnit TestCase helper methods for use inside reusable test traits. Lets traits call mocking, expectations, and other TestCase APIs without extending TestCase directly; assertions are via PHPUnit\Framework\Assert.
Installation:
composer require maks3w/phpunit-methods-trait
Add the trait to your test trait or base test class:
use Maks3w\PhpUnitMethodsTrait\Framework\TestCaseTrait;
First Use Case:
Use the trait in a test trait to access PHPUnit methods (e.g., mocking, assertions) without requiring TestCase inheritance:
trait MockHelperTrait {
use TestCaseTrait;
public function createMock(string $className): object {
return $this->getMockBuilder($className)->getMock();
}
}
Test Traits for Reusable Logic: Extend the trait in a test trait to provide mocking/assertion helpers:
trait DatabaseTestTrait {
use TestCaseTrait;
protected function mockDatabaseConnection(): void {
$this->getMockBuilder(Connection::class)
->disableOriginalConstructor()
->getMock();
}
}
Integration with Custom Test Cases: Use the trait in a base test class to avoid repeating method calls:
abstract class BaseTestCase extends TestCase {
use TestCaseTrait;
}
Static Assertions:
For static assertions (e.g., Assert::assertTrue()), import PHPUnit\Framework\Assert directly:
use PHPUnit\Framework\Assert;
trait AssertionTrait {
public function assertResponseIsValid(): void {
Assert::assertTrue($this->response->isSuccessful());
}
}
getMockBuilder(), createMock(), assert*(), expects(), etc.Static Assertions:
Assert methods (e.g., Assert::assertTrue()).PHPUnit\Framework\Assert manually in your trait/class.PHPUnit Version Mismatch:
Trait Conflicts:
TestCaseTrait, method conflicts may arise.Missing Methods:
If a method (e.g., assertArrayHasKey()) isn’t autocompleted:
Assert method (import manually).IDE Not Recognizing Methods:
File > Invalidate Caches).used in the correct scope (not inside a class method).Customize Trait Methods: Override methods in your trait to add logic:
trait CustomMockTrait {
use TestCaseTrait;
public function mockWithDefault(): object {
return $this->getMockBuilder($this->className)
->setMethods(['defaultMethod'])
->getMock();
}
}
Add New PHPUnit Methods:
If a missing method is needed, fork the package and extend TestCaseTrait:
trait ExtendedTestCaseTrait {
use TestCaseTrait, \Maks3w\PhpUnitMethodsTrait\Framework\AssertTrait;
}
Combine with Other Traits:
Use alongside Laravel’s RefreshDatabase or WithFaker traits:
trait FeatureTestTrait {
use TestCaseTrait, RefreshDatabase;
}
How can I help you explore Laravel packages today?