doutan6286 2018-03-27 03:32 采纳率: 100%
浏览 43
已采纳

Laravel - 单元测试 - 整数数据类型的变量以字符串形式出现,而单元测试和单元测试失败

I'm new to Laravel and PHP. I have created a migration 'Car' table with columns id, Make, Model, Year.I have used the seeder to make 50 cars using faker. I have written a unit test to test the data type of the year property to be int, but my unit test is failing. Could anyone pls help me on this?

Migration table:
 public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->increments('id');
            $table->string('make');
            $table->string('model');
            $table-> integer('year');
            $table->timestamps();
        });

Factory:
$factory->define(App\Car::class, function (Faker $faker) {
    return [
        'make' => $faker->randomElement($array = array ('Ford','Honda','Toyota')),
        'model' => $faker->name,
        'year'   => $faker->year($max = 'now'),

Seeder
    public function run()
    {
        factory(App\Car::class, 50)->create()->each(function ($car) 
}

Unit test 
 public function testCarYearDataType()
    {
        $car = Car::find(1);
        dd($car->year);
      dd(gettype($car->Year));
       this->assertInternalType('int',$car->Year);
    }
  • 写回答

3条回答 默认 最新

  • dongqiao6730 2018-03-27 04:32
    关注

    Not sure datatype is the right kind of test but anyway

    The key thing to remember is you need to have a different database for testing my case I use memory so my phpunit.xml looks like the following

    <env name="APP_ENV" value="testing"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="QUEUE_DRIVER" value="sync"/>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>
    

    The you will have your test class. In your case I would call it CarTest.php

    <?php 
    
    namespace Tests\Unit;
    
    use Illuminate\Foundation\Testing\DatabaseTransactions;
    use Tests\TestCase;
    
    
    class CarTest extends TestCase {
    
        use DatabaseTransactions;
        
       
        
        public function testCarYearDataType()
        {
        
         //just create 1 car as all the cars will have same data type anyway
          factory(App\Car::class)->create(); 
    
           this->assertInternalType('int', gettype(Car::first()->year));
        }
    }

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答