I created a thread about Testing Services with phpunit inside symfony. Now that I figured it out, I have the following problem. I have this service, which get’s User Cart by ID.
class CartService
{
private CartRepository $cartRepository;
private ManagerRegistry $managerRegistry;
private CartItemRepository $cartItemRepository;
private Security $security;
public function __construct(Security $security, CartItemRepository $cartItemRepository, CartRepository $cartRepository, ManagerRegistry $managerRegistry)
{
$this->cartItemRepository = $cartItemRepository;
$this->cartRepository = $cartRepository;
$this->managerRegistry = $managerRegistry;
$this->security = $security;
}
/**
* Get Cart by ID
*
* @return Cart|null
*/
public function getCartByUserId(): ?Cart
{
$user = $this->security->getUser();
return $this->cartRepository->findOneBy(['customer' => $user]);
}
Since I am not logged in, I want to test this method with custom $user ID. I tried to add integer to $user variable inside CartServiceTest.php, but I get NULL as result.
class CartServiceTest extends KernelTestCase
{
public CartService $cartService;
public function setUp(): void
{
self::bootKernel();
$container = static::getContainer();
$this->cartService = $container->get(CartService::class);
}
public function testShowCart()
{
$user = 11; // Here
$cart = $this->cartService->getCartByUserId();
dump($cart);
}
}
Result:
PHPUnit 9.5.21 #StandWithUkraine
Testing App\Tests\CartServiceTest
^ null
R
As soon as I change my CartService, and add $user as argument, works, and I get Cart Object back.
/**
* Get Cart by ID
*
* @return Cart|null
*/
public function getCartByUserId($user): ?Cart
{
return $this->cartRepository->findOneBy(['customer' => $user]);
}
How can I change $user value inside unit testing? So I can run test with different user id’s?
Securityobject which will return a valid user id when it'sgetUser()method is called? It is theCartclass you would like to the and not theSecurityclass. Read more about mocking here: phpunit.readthedocs.io/en/9.5/test-doubles.html