First Friction with Coverage and PHPStan
While building Sunny, I’ve been vaguely checking my code coverage and checking PHPstan and seeing what I’m “forced” to write to get to 100% coverage or to make stan happy. So far, everything it has found has been something I missed. I’ve encountered an instance where these tools encourage me to break my patterns. I probably wouldn’t have written a test for this without coverage or PHPstan.
Below is a computed property from the CreateRecipe
component:
#[Computed]
public function previewUrl(): ?string
{
if ($this->form->image) {
return $this->form->image->temporaryUrl();
}
}
Using the code above, the CreateRecipe class is 100% covered. However, PHPStan is angry that there isn’t a return statement.
To make stan happy, I added a return, however doing so decreased the code coverage because I hadn’t added a test specifically testing that a null
can be returned.
So now the method looks like this:
#[Computed]
public function previewUrl(): ?string
{
if ($this->form->image) {
return $this->form->image->temporaryUrl();
}
return null;
}
This is now going to force me to write a test that the previewUrl()
function can return null
.
Adding the following test increased the coverage back to 100%:
test('previewUrl is null by default', function () {
Livewire::test(CreateRecipe::class)
->assertOk()
->assertSet('previewUrl', null);
});
However, I think this test is useless since it tests the language, not my feature implementation.
Here are the classes as of December 22nd, 2024:
What do you think? Is the previewUrl is null be default
test useless? How would you improve it?