【发布时间】:2018-10-18 08:13:02
【问题描述】:
我想测试一下这个功能:
public function store(array $input){
\DB::beginTransaction();
try{
$input['name'] = $input['first_name'].$input['last_name'];
$input['password'] = str_random(7);
$user = $this->model->create($input);
$role_user = new RoleUser();
$role_user->role_id = $input['role_id'];
$role_user->user_id = $user->id;
$role_user->save();
\DB::commit();
return $user;
}catch (Exception $e){
\DB::rollback();
return false;
}
}
这是我的测试
/** @test */
public function testUserRepoStoreFail()
{
$roleUser = factory(\App\Models\RoleUser::class)->create();
$role = factory(\App\Models\Role::class)->create();
$this->expectException(Exception::class);
$data =[
'role_id' => $role->id,
'name' => $this->faker->name,
'first_name' => $this->faker->name,
'last_name' => $this->faker->name,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => str_random(10),
];
$rep = new UserRepositoryEloquent($this->container);
//
$user = $rep->store($data);
}
我删除了电子邮件以使商店功能失败
当我这样做时,我得到:
1) Tests\Unit\AuthTest::testUserRepoStoreFail 断言抛出“Exception”类型的异常失败。**
【问题讨论】:
-
这基本上是说您期望使用
$this->expectException(Exception::class)会出现异常,但是当您使用store()方法时,不会抛出异常。 -
另外,如果你没有,在你的类的顶部说
use Exception;,就在命名空间之后,或者在catch()和你的测试中使用\Exception而不是Exception断言。如果您不执行其中一项,您的异常命名空间将与使用它的类相同,并且两个异常将不匹配
标签: javascript php laravel phpunit