symfony - 使用 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());
}
解决方案
推荐阅读
- angular - 可以将“客户列表”添加到“客户”模块
- python - 从列python获取元素
- c++ - 指向单例和内存泄漏的原始指针:Xcode 没有显示任何内存泄漏
- c# - 将一个表达式“注入”另一个表达式
- groovy - Groovy groupBy 可变字符序列
- node.js - 使用猫鼬(NodeJS)连接到 MongoDB Atlas 集群时出现问题
- servicestack - 如何配置客户端以使用 authsecret 进行访问?
- python - 如何从具有日期时间索引的熊猫数据框中获取选定列的下个月的值
- apache-spark - 如何确保在 Spark 流中使用 Elasticsearch-Hadoop 连接器写入 Elasticsearch 集成的所有文档
- mongodb - Mongo 查询过滤器 $lookup 未正确过滤