首页 > 解决方案 > 使用 Symfony 和 PHPUnit 进行单元测试时如何获取实体实例?

问题描述

正如标题所说,我正在尝试在环境中进行单元测试。但是,被测类中包含的方法需要一个实体实例作为参数。因此,我试图在扩展 TestCase 类的通用自制测试类中​​获取上述实体,但我不知道该怎么做。我对功能测试的经验很少。我当时用的是灯具,所以我猜这次我也应该使用灯具。那是对的吗?如果你也能教我如何做到这一点,我将不胜感激。

请让我知道,即使是一点点信息。

下面是测试类,以及测试目标的接口。

附言。我们正在使用 nelmio/alice 捆绑包。

<?php

declare(strict_types=1);

namespace xxx\xxxx\Tests\Customize\Server\AlladinOffice;

use Codeception\PHPUnit\TestCase;
use Customize\Service\AlladinOffice\CodeFormatter;
use Customize\Service\AlladinOffice\CustomerCode;
use Doctrine\Common\Persistence\ObjectManager;
use Eccube\Repository\CustomerRepository;
use PHPUnit\Framework\MockObject\MockObject;
use Proxies\__CG__\Eccube\Entity\Customer;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class CustomerCodeTest extends KernelTestCase
{
    /**
     * @var CustomerCode
     */
    private $sut;

    /**
     * @var CustomerRepository|MockObject
     */
    private $customerRepository;

    protected function setUp()
    {
        $codeFormatter = new CodeFormatter();
        $this->sut = new CustomerCode($codeFormatter);
        $this->customerRepository = $this->createMock(CustomerRepository::class);
        parent::setUp();
    }

    public function testGetCustomerCode()
    {
        $actual = $this->sut->getCustomerCode(null);
        $expected = 1000000000;
        $this->assertEquals($expected, $actual);

//        $customer = $this->customerRepository->findBy([], ['id' => 'ASC']);
//        dump($customer);exit();
//        $actual = $this->sut->getCustomerCode($customer);
        $customer = new Customer;
        //$customer->set

        //$this->customerRepository
            //->expects($this->any())
            //->method('find')
            //->willReturn($);
    }
}

<?php

declare(strict_types=1);

namespace Customize\Service\AlladinOffice;

use Eccube\Entity\Customer;

interface CustomerCodeInterface
{
    public function getCustomerCode(?Customer $customer): string;

    public function getChannelCode(?Customer $customer): string;

    public function getRankCode(?Customer $customer): string;
}

例如一个详细的测试方法。

    public function getCustomerCode(?Customer $customer): string
    {
        if (!$customer) {
            return self::DEFAULT_CUSTOMER_CODE;
        }
        $customerRank = $customer->getXxxCustomer()->getCustomerRank();

        $customerChannel = $customerRank ? $customerRank->getCustomerChannel() : null;
        if (!$customerChannel || !$customerChannel->isExportToAO()) {
            return self::DEFAULT_CUSTOMER_CODE;
        }

        return $this->formatter->getCustomerCodeFromCustomerId($customer->getId());
    }

标签: symfonyphpunit

解决方案


推荐阅读