bksurik's avatar

Unit Tests for Creation Methods with Business Rule Validation

How to write a unit test for a creation method with business rules checking, using standard Laravel tools ?

class UserRepository implements IUserRepository {

    public function __construct(
        private readonly IBusinessRulesValidation $businessRulesValidation,
    ) {}

    public function create(Request $user) {
        $this->businessRulesValidation->uniqueValueChecker(tableName: 'users', fieldName: 'name', value: $user['name']);
    
       return User::create($user->toArray());
    }
}
class BusinessRulesValidationRepository implements IBusinessRulesValidation {
    public function uniqueValueChecker(string $tableName, string $fieldName, string $value, ?int $excludedId = null): void {
        $result = DB::table($tableName)
            ->whereRaw('LOWER('.$fieldName.') = LOWER(?)', [$value])
            ->whereNot('id', $excludedId)
            ->exists();

        if ($result) {
            throw new BusinessLogicException(message: "An entry with the same $value already exists.");
        }
    }
}
0 likes
0 replies

Please or to participate in this conversation.