我是Laravel和PHP的新手。我创建了一个迁移' Car'表ID列,制作,模型,年。我使用播种机使用faker制作50辆汽车。 我已经编写了一个单元测试来测试year属性的数据类型为int,但是我的单元测试失败了。任何人都可以帮我这个吗?
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);
}
答案 0 :(得分:1)
不确定数据类型是否是正确的测试,但无论如何
要记住的关键是你需要有一个不同的数据库来测试我的情况我使用内存所以我的phpunit.xml看起来如下
<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:"/>
您将拥有测试课程。在你的情况下,我称之为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));
}
}
答案 1 :(得分:0)
尝试更新模型以防止与typecasting碰撞:
/**
* The attributes that are not mass assignable.
*
* @var array
*/
protected $guarded = [
'id',
];
/**
* Typecasting is awesome and it prevents errors.
*
* @var array
*/
protected $casts = [
'make' => 'string',
'model' => 'string',
'year' => 'integer',
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'created_at',
'updated_at',
];
答案 2 :(得分:0)
您的问题可能是拼写错误,但字段区分大小写。 href=""
会在<?php
$url = "http://www.example.com/download/s/eyJjdCI6IkFpc003OERmME1uS3dhR1BQcXg1ckE9PSIsIml2IjoiNzg0OGI5NWRmMmRjZDg0ZjFlMjVjYTM3MjY1MjdjMTUiLCJzIjoiYjU1NTIyN2Q2MmJiODAyMSJ9.mp3";
?>
<a id="downloadLink" href="<?php echo $url; ?>">Text To Show</a>
字段中显示您的值。由于您没有$car->year
字段,year
会向您$car->Year
提供。
对于从数据库返回的字段类型,可能因底层数据库和用于访问该数据库的驱动程序而异。如果您想避免所有不确定性,则需要将字段添加到模型的null
属性中:
Year
现在,访问时,该字段将始终强制转换为PHP整数。