Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

How to disable casting during testing

I need to figure out a way to unit test that a user has a status property on the model. With this model, I have a custom enum cast object coming from the package listed below. Currently, my test fails at the creation of the user object. The reason being is that it is looking for a value of example as a valid enum valid. Since there is not then it errors. What

I want to do is being to add to the test to have it ignore that specific cast for the purpose of this test. How is that possible?

https://github.com/mad-web/laravel-enum

Error given from test.

UnexpectedValueException: Value 'example' is not part of the enum App\Enums\UserStatus

App\Models\User.php

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
    'status' => Status::class,
];

tests/Unit/Models/UserTest.php

public function a_user_has_a_status()
{
    $user = new User(['status' => 'example']);

    $this->assertEquals('example', $user->getRawOriginal('status'));
}
0 likes
12 replies
sirhxalot's avatar

In Laravel 7 you should use: getRawOriginal(). Before you can use getOrginal()

jrdavidson's avatar

The problem isn't with the assertion. The problem is that it doesn't successfully create the model. It errors on the creation of the model due to the cast.

Also notice in my test I am using getRawOriginal()

jrdavidson's avatar

I'm using 7.2 I'll also add this to the original post.

UnexpectedValueException: Value 'example' is not part of the enum App\Enums\UserStatus

sirhxalot's avatar

This is where the error will be thrown:

$user = new User(['status' => 'example']);

Since you are casting you must convert the value to App\Enums\UserStatus you can not assign a string.

jrdavidson's avatar

I know that. My question is how can I disable casting during testing.

jrdavidson's avatar

@sti3bas Actually I jumped the gun a second. The assertion gives me null for the $user->getRawOriginal('status'). How could that be?

Sti3bas's avatar

@xtremer360 pass true as a second param: $user->setRawAttributes(['status' => 'example'], true);

jrdavidson's avatar

Yeah I took a second look to understand what the second param did. Makes sense. Thank you.

Please or to participate in this conversation.