我有這個方法:
public function findAllBy(?string $categoryId): array
{
$qb = $this->entityManager->createQueryBuilder()
->select('p')
->from(Product::class, 'p');
if (null !== $categoryId) {
$qb->from(Category::class, 'cc')
->join(CategoryProduct::class, 'cp', Join::WITH, 'p.id = cp.product_id')
->join(Category::class, 'c', Join::WITH, 'cp.category_id = c.id')
->where('cc.id = :id')
->andWhere('cc.left <= c.left')
->andWhere('cc.right >= c.right')
->setParameter('id', $categoryId, 'uuid');
}
return $qb->getQuery()->getResult();
}
我正在嘗試以這種方式對其進行測驗(顯然不是正確的):
public function testFindAllProductsByFilters():void
{
$entityRepositoryMock = $this->createMock(EntityRepository::class);
$entityManagerMock = $this->createMock(EntityManagerInterface::class);
$entityManagerMock->expects($this->once())
->method('getRepository')
->with(Product::class)
->willReturn($entityRepositoryMock);
$entityManagerMock->expects($this->once())
->method('createQueryBuilder')
->willReturn($entityRepositoryMock);
$this->repository = new DoctrineProductRepository($entityManagerMock);
$this->assertIsArray($this->repository->findAllBy(ProductFactory::CATEGORY_ID_FIRST));
}
我得到的錯誤:1)
App\Tests\Unit\Infrastructure\Domain\Model\Product\DoctrineProductRepositoryTest::testFindAllProductsByFilters 錯誤:在 null 上呼叫成員函式 from()
這段代碼甚至可以通過 Unit Test 測驗嗎?
uj5u.com熱心網友回復:
因為你不應該嘲笑你不擁有的東西,所以我的建議是避免在這種情況下進行單元測驗。此外,當您正在測驗實作而不是 SUT 的行為時,我不會使用(濫用)模擬(通常是測驗替身)。
讓我們看一個例子
class Foo()
{
public function doSomething(): int
{
// some heavy logic here
}
}
class Bar()
{
public function doSomething(Foo $foo): int
{
$result = $foo->doSomething();
// other elaboration upon $result
}
}
當然,這是一個故意的微不足道的例子。如果你在Bar測驗中使用測驗替身,你會寫類似`
$fooMock->expects($this->once())
->method('doSomething')
->willReturn(1);
假設Foo改變了它的公共 API,重命名doSomething為doSomethingElse. 發生什么了?即使Foo行為根本沒有改變,您也需要更改測驗。
如前所述,這是一個微不足道的例子,但應該給你一個想法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/475562.html
下一篇:如何合并重復項
