Courses

[NEW] Testing in Laravel 11: Advanced Level

Testing Classes with assertInstanceOf

Let's examine another assertion called assertInstanceOf(), which checks whether the object's class is correct.


Practical Pest Example

To demonstrate that, I created a product Service with just one product creation method. It's a very simplified example, but it will help you understand the idea.

app/Service/ProductService.php:

namespace App\Services;
 
use App\Models\Product;
use Brick\Math\Exception\NumberFormatException;
 
class ProductService
{
public function create(string $name, int $price): Product
{
if ($price > 1_000_000) {
throw new NumberFormatException('Price too big');
}
 
return Product::create([
'name' => $name,
'price' => $price,
]);
}
}

So, this method should return a Product Model. But if something goes wrong, it may return an Exception.

In the test, we will call that Service, check that it is successful with our product data, and check the returned object class. Is it a Product?

use App\Models\Product;
 
it('returns product from the product service create method', function () {
$product = (new ProductService())->create('Test product', 1234);
 
expect($product)->toBeInstanceOf(Product::class);
});


PHPUnit Example

With PHPUnit, you use the assertInstanceOf() assertion similarly.

use App\Models\Product;
 
class ProductsTest extends TestCase
{
// ...
 
public function test_product_service_create_returns_product(): void
{
$product = (new ProductService())->create('Test product', 1234);
 
$this->assertInstanceOf(Product::class, $product);
}
}

Also, with PHPUnit, the assertInstanceOf() can be used to check if an Exception was thrown by simulating a try-catch.

use App\Models\Product;
use Brick\Math\Exception\NumberFormatException;
 
class ProductsTest extends TestCase
{
// ...
 
public function test_product_service_create_returns_product(): void
{
$product = (new ProductService())->create('Test product', 1234);
 
$this->assertInstanceOf(Product::class, $product);
}
 
public function test_product_service_create_validation(): void
{
try {
$product = (new ProductService())->create('Test product', 1234567);
} catch (\Exception $e) {
$this->assertInstanceOf(NumberFormatException::class, $e);
}
}
}

No comments or questions yet...