Skip to content
Advertisement

change parameter value of dependent method in phpunit

i wrote a sample test case for collection like class but weird thing about this is in my testAdd method that i add a item in CustomCollectionService and it changed my parameter too. how can this happend?

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);
}
}

and this is my test:

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());
    }
}

Advertisement

Answer

Because it is an object. So when you pass the $col object to the CollectionService and call the add method within the CollectionService, it is still the $col object from your test method that is being used.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement