ecomdev/phpspec-magento-di-adapter

一个用于简化使用PHPSpec编写示例的Magento\Framework的DI(依赖注入)功能的适配器。不使用ObjectManager,仅模拟其部分功能

1.0.0 2016-09-15 10:18 UTC

This package is auto-updated.

Last update: 2024-08-27 21:41:01 UTC


README

这个小巧的PHPSpec扩展允许您通过利用 Magento\Framework\ObjectManager 的生成器,使测试Magento 2.0模块变得更加容易。

为什么?

不使用 ObjectManager 的PHPSpec示例的原因

  1. 它很重,并且需要模拟整个文件系统来运行一个简单的spec示例。
  2. 依赖于ObjectManager是一个坏主意,因为你不想测试DI的覆盖。
  3. 不需要数据库的简单模块不需要完全功能化的对象管理器
  4. 将您的业务逻辑适配到另一个框架将只需要您实例化生成的类,而不是依赖于整个ObjectManager库。

支持的生成器

  • 工厂
  • 仓库
  • 转换器
  • 持久化器
  • 映射器
  • 搜索结果

安装

  1. 通过composer安装

    composer require --dev ecomdev/phpspec-magento-di-adapter
  2. 添加到您的 phpspec.yml 中

    extensions:
       - EcomDev\PHPSpec\MagentoDiAdapter\Extension

使用

确保在编写示例时,为自动生成的类指定完全限定类名。

<?php

namespace spec\Acme\CustomMagentoModule\Model;

use Magento\Catalog\Model\Product;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class ProductManagerSpec extends ObjectBehavior
{
    private $productFactory; 
    
    function let(ProductFactory $factory) {
        $this->productFactory = $factory;    
        $this->beConstructedWith($factory);
    }
    
    function it_creates_items_via_product_factory(Product $product)
    {
        $this->productFactory->create()->willReturn($product)->shouldBeCalled();
        $this->someCreationLogic();
    }
}

这种方法不会得到您想要的结果,因为PHP默认情况下会在同一个命名空间内查找未定义的类。所以它不会生成 Magento\Catalog\Model\ProductFactory 类,而是生成一个 spec\Acme\CustomMagentoModule\Model\ProductFactory 类,这绝对不是期望的行为。

为了解决这个问题,确保在方法签名中指定完全限定名称,或者通过文件头部的 use 操作符指定。

<?php

namespace spec\Acme\CustomMagentoModule\Model;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductFactory; // This class will be automatically generated
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class ProductManagerSpec extends ObjectBehavior
{
    private $productFactory; 
    
    function let(ProductFactory $factory) {
        $this->productFactory = $factory;    
        $this->beConstructedWith($factory);
    }
    
    function it_creates_items_via_product_factory(Product $product)
    {
        $this->productFactory->create()->willReturn($product)->shouldBeCalled();
        $this->someCreationLogic();
    }
}

贡献

基于develop分支创建一个pull request