【问题标题】:Lumen - Using factory() function in tests make error - Undefined FunctionLumen - 在测试中使用 factory() 函数会出错 - 未定义函数
【发布时间】:2022-01-21 00:01:59
【问题描述】:

我正在使用 Lumen 8.3,想在我的测试中使用 factory() 函数,它给了我 Undefined Function ,Docs of Lumen 没有什么用处

我错过了什么吗?

class ProductTest extends TestCase
{

    public function test_if_can_send_products_list(){
        $products = factory('App/Products',5)->make();
        $this->json('post','/payouts',$products)
        ->seeJson([
            'created' => true,
        ]);

    }
}

->

Error: Call to undefined function factory()

【问题讨论】:

    标签: laravel testing phpunit tdd lumen


    【解决方案1】:

    我只是在app.php 文件中取消了这些行的注释

    $app->withFacades();
    
    $app->withEloquent();
    

    【讨论】:

      【解决方案2】:

      最好使用这样的直接类:

      $products = factory(Products::class, 5)->create();
      

      不要忘记添加Products 模型用法(命名空间)。

      编辑

      你应该创建工厂:

      <?php
      
      namespace Database\Factories;
      
      use App\Products;
      use Illuminate\Database\Eloquent\Factories\Factory;
      use Illuminate\Support\Str;
      
      class ProductFactory extends Factory
      {
          protected $model = Products::class;
      
          public function definition(): array
          {
              return [
                  'name' => $this->faker->unique()->userName()
              ];
          }
      }
      

      并将HasFactory Trait 添加到您的模型中:

      use Illuminate\Database\Eloquent\Factories\HasFactory;
      class Products extends Model {
         use HasFactory;
      }
      

      你也可以这样使用

      Products::factory()->count(5)->make();
      

      【讨论】:

      • Tnx,但它没有回答我的问题。 factory 未定义!
      • @John 我更新了我的答案,希望对您有所帮助
      • tnx,我的模型已经有了那个工厂类。但factory() 功能不起作用。使用了您提到的特征(HasFactory)但没有帮助,甚至我的 IDE 也警告我未定义的功能。 (factory 函数实际上包含在 HasFactory 特征中,但不知道为什么它给我 undefined)
      • 你试过用这个吗:Products::factory()-&gt;count(5)-&gt;make(); 输出是什么?
      • 抱歉错过了,是的,它会起作用,但是为什么流明文档中提到的东西不起作用?
      猜你喜欢
      • 2021-05-08
      • 2021-08-05
      • 2020-12-28
      • 1970-01-01
      • 2019-12-10
      • 2020-02-14
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多