Summer Sale! All accounts are 50% off this week.

CLab's avatar
Level 3

When using faker geting Unknown Formatter error

I have a container factory which is as follows:

<?php

namespace Database\Factories;

use App\Models\Container;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Arr;

class ContainerFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
         $preparationDate = $this->faker->dateTimeBetween('-5 years', '-3 weeks');
         .
         .
         .
         return [
             .
             .
             'preparation_date' => $preparationDate,
          ];
     }
}

When I use tinker, this produces an appropriate container.

However, when I use it in a test class method (i.e. not a test but a helper function) like:

namespace Tests\Feature\Samples;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class FormValidationTest extends TestCase
{

   /* Number of test cases here not shown
    *
   */
    
   // This function is a helper for my data provider for my tests.
    public function generatePostData(string $path, $value)
    {
        $container = Container::factory()->create(); // This line gives error
          .
          .
          . 
         
          return [ 
                .
                .
                .
               'container' => $container
           ];
      }
}

It throws the error:

  The data provider specified for Tests\Feature\Samples\FormValidationTest ::test_user_cant_store_invalid_samples is invalid.
InvalidArgumentException: Unknown formatter "dateTimeBetween"

Edit: The same $container = Container::factory()->create(); works fine within a test method in the same file like

public function test_a_feature() {
   $container = Container::factory()->create(); // This works when put in a test
}

How can I create models in a separate function?

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

Don't use Factories in the DataProvider methods, because the DataProviders are actually executed before the Test Suite is even started (set up). Also, the framework has not been bootstrapped yet (which is done in the setUp method). There is a caveat heading in the following article which explains in more detail along with the workaround (using a Closure):

https://tighten.co/blog/tidying-up-your-phpunit-tests-with-data-providers/

CLab's avatar
Level 3

@tykus Thanks for the response. I saw the article and the workaround went a little over my head. Could you explain what they are talking about? Sorry for being such a noob.

Please or to participate in this conversation.