'Unit (real unit test) of test laravel relationship
Background
- Framework: laravel 9.x
- PHP 8.0
- Continuous integration (Travis CI etc)
I am working on a project that is legally very sensitive, so testing is vital.
Due to project requirements, the project requires 100% unit testing and code coverage. This is a project requirement, even if it is relatively pointless in a few % of the cases. Just to be clear: the relationships work as expected in the functional/feature testing, however... this is for Unit testing. Traditional, no dependencies (mocks etc) unit tests.
To be clear: this is an exercise in reaching 100% coverage NOT necessarily "good" testing. Adding a "testing ignore" line needs to be justified, so this "suboptimal test" is still the best option for the project.
Question
How is it possible to UNIT test the following function:
use Illuminate\Database\Eloquent\Model;
// declaration: normal laravel model
class Product extends Model
/**
* @return BelongsTo
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
This needs to be a Unit test. This testing will be run without a database connection, preferably without any other classes (except for mocks).
Solution 1:[1]
You would unit test a relationship the same you would anything else. No mocks needed...
- Setup your data;
- Executing your function; and
- Assert your results.
/** @test */
public function a_product_can_access_its_associated_user()
{
//Setup
$product = Product::factory()
->for(User::factory()->create())
->create();
//Executing & Asserting
$this->assertTrue($product->user()->exists());
}
For more information on creating models with relationships in Laravel, review their documentation here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Savlon |