我正在使用Laravel为IOS应用程序构建API。我遇到的主要问题是使用PHPUnit测试web应用程序和内置的Laravel测试。
我的流程是: 1.用户有一个帐户。2.用户需要经过身份验证才能执行任何操作。
假设我有一组用户组,并且有一个用户(所有者)可以管理属于他们组的成员。我想测试用户将其他成员添加到组中的能力。
我有一个名为testAddGroupMemberPass()的测试方法,它应该
要断言所有者可以添加用户,您必须首先创建所有者,其次创建组,然后创建要添加到组中的用户,最后您可以尝试向API发出请求以实际添加该用户。
问题是,在前三个步骤中,可能会遇到与将成员添加到组中的过程完全无关的各种问题,例如用户名和电子邮件的唯一约束。
那么,我目前的做法有什么问题呢?我一直被告知,测试应该完全独立于彼此,所以尝试使用以前的测试生成的用户和组是没有意义的AFAIK。
发布于 2016-01-05 01:46:28
您可以将1、2和3抽象到一个基本测试类中,并在测试这些特定功能的测试中使用相同的方法。
例如:
// TestCase.php
protected function createOwner()
{
return factory(User::class)->create();
}
protected function createGroup($owner)
{
// You didn't show this as a factory, but I figured you might want that
$group = factory(Group::class)->create();
$group->owner()->associate($owner);
$group->save();
return $group;
}
protected function createUser()
{
return factory(User::class)->create();
}
// In the file you mention above (should be extending TestCase.php)
public function testAddGroupMemberPass()
{
// 1. create owner
$owner = $this->createOwner();
$token = JWTAuth::fromUser($owner);
// 2. create group and attach user
$group = $this->createGroup($owner);
// 3. create the member to be
$user = $this->createUser();
// 4. attempt attach the member to the group
$this->edit('/groups/' . $group->id . '/add-member/' . $user->username . '?token=' . $token)
->seeJson(['success' => true]);
}这些方法可用于其他测试,如:
// In UserTest.php (also extends TestCase.php)
public function testItCreatesAUser()
{
$user = $this->createUser();
$this->seeInDatabase('users', $user);
}事实是,如果您需要您的世界看起来一定的方式,并且您正在进行某种功能或集成测试,那么您需要在某个地方封装这个逻辑。将其移动到基类将有助于删除重复的功能。
https://stackoverflow.com/questions/34601742
复制相似问题