I am trying to test if an item can be added to my shopping list. I am unsure of where I am going wrong and the error I am getting is:
ArgumentCountError : Too few arguments to function Tests\Unit\Entities\ShoppingListTest::testAddItem(), 0 passed in
Which is confusing me because I have passed arguments where they are needed? I am new to unit testing and just need some guidance. I also realise that I may of picked the wrong assert to be called so any input on that would be helpful! Here is my test:
public function testAddItem(string $name): void
{
//Arrange: Given an item to add to the shopping list
$items = [new ShoppingItem('lettuce')];
$list = new ShoppingList('my-groceries', $items);
//Act: Add the item to the list
$list->addItem($name);
//Assert: Check to see if the item was added to the list
$this->assertContains($items, $list, 'Does not contain lettuce.');
}
And here is my shopping list class that contains the function I am testing:
class ShoppingList implements \iterable
{
/**
* @var string
*/
private string $name;
/**
* @var ShoppingItem[]
*/
private array $items;
public function __construct(string $name, array $items)
{
$this->name = $name;
foreach($items as $item) {
if(!$item instanceof ShoppingItem) {
throw new \InvalidArgumentException("Expecting only shopping items.");
}
}
$this->items = $items;
}
public function getName(): string
{
return $this->name;
}
public function getItems(): array
{
return $this->items;
}
public function addItem(string $name): void
{
$item = new ShoppingItem($name);
$this->items[] = $item;
}
public function checkOffItem(string $name): void
{
$item = $this->findItemByName($name);
if($item) {
$item->checkOffItem();
return;
}
throw new \LogicException("There is no item on this list called $name.");
}
private function findItemByName(string $name): ?ShoppingItem
{
foreach($this->items as $item) {
if($item->getName() === $name) {
return $item;
}
}
return null;
}
CodePudding user response:
Here is the passed test. I didn't add another item to the list.
public function testAddItem(): void
{
//Arrange: Given an item to add to the shopping list
$items = [new ShoppingItem('lettuce')];
$list = new ShoppingList('my-groceries', $items);
//Act: Add the item to the list
$actual = $list->getItems();
$list->addItem('cabbage');
//Assert: Check to see if the item was added to the list
$this->assertEquals($items, $actual);
}