更改phpunit中依赖方法的参数值

change parameter value of dependent method in phpunit

我为 class 之类的集合编写了一个示例测试用例,但奇怪的是在我的 testAdd 方法中,我在 CustomCollectionService 中添加了一个项目,它也改变了我的参数.怎么会这样?

class CustomCollectionService
{
/**
 * @var Collection $collection
 */
public $collection;
public function makeCollection($arr)
{
    $this->collection = collect($arr);
}

/**
 * @param Collection $collection
 */
public function setCollection(Collection $collection): void
{
    $this->collection = $collection;
}


/**
 * @return mixed
 */
public function getCollection()
{
    return $this->collection;
}

public function add($item)
{
    return $this->collection->add($item);
}
}

这是我的测试:

class CustomCollectionTest extends TestCase
{
    public $collectionService;
    public  $collection;
    protected function setUp(): void
    {
        $this->collectionService = new CustomCollectionService();
    }

    public function testCollectionCreator()
    {
        $arr = ['sina','1',5];
        $this->assertIsArray($arr);
        return $arr;
    }

    /**
     * @param $arr
     * @depends testCollectionCreator
     */
    public function testAction($arr)
    {
        $this->collectionService->makeCollection($arr);
        $this->assertIsArray($this->collectionService->getCollection()->toArray());
        return $this->collectionService->getCollection();
    }

    /**
     * @depends testAction
     */
    public function testAdd($col)
    {
        $actualCount = $col->count();
        $this->collectionService->setCollection($col);
        $manipulatedCollection = $this->collectionService->add(['xx']);
        dump($actualCount); // 3
        dump($col->count()); //4
        $this->assertEquals($actualCount+1, $manipulatedCollection->count());
    }
}

因为它是一个对象。因此,当您将 $col 对象传递给 CollectionService 并在 CollectionService 中调用 add 方法时,它仍然是您的测试方法中的 $col 对象正在使用中。