【问题标题】:How can a laravel session be used within a phpspec test如何在 phpspec 测试中使用 laravel 会话
【发布时间】:2014-08-22 23:47:53
【问题描述】:

我正在尝试使用 phpspec 测试一个非常简单的类。

应该测试的类的一些方法

/**
 * @param Store $session
 */
function __construct(Store $session)
{
    $this->session = $session;
}

/**
 * @param Store $session
 */
function __construct(Store $session)
{
    $this->session = $session;
}

/**
 * Set the current order id
 *
 * @param $orderId
 */
public function setCurrentOrderId($orderId)
{
    $this->session->set($this->sessionVariableName, $orderId);

    return $this;
}

/**
 * Get the current order id
 *
 * @return mixed
 */
public function getCurrentOrderId()
{
    return $this->session->get($this->sessionVariableName);
}

还有一部分测试

use Illuminate\Session\Store;


class CheckoutSpec extends ObjectBehavior
{
    function let(Store $session)
    {
        $this->beConstructedWith($session);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Spatie\Checkout\Checkout');
    }

    function it_stores_an_orderId()
    {
        $this->setCurrentOrderId('testvalue');

        $this->getCurrentOrderId()->shouldReturn('testvalue');

    }
}

不幸的是,it_stores_an_orderId 上的测试失败,出现此错误expected "testvalue", but got null.

setCurrentOrderIdgetCurrentOrderId 方法在工匠的修补程序中使用时,它们工作得很好。

在我的测试环境中,会话的设置似乎有问题。

如何解决这个问题?

【问题讨论】:

    标签: php session testing laravel-4 phpspec


    【解决方案1】:

    实际上,您尝试测试的不仅仅是您的班级。 PHPSpec 规范(以及一般的单元测试)旨在独立运行。

    在这种情况下,您真正​​想要的是确保您的课程按预期工作,不是吗?简单地模拟 Store 类,只检查它的必要方法是否被调用并模拟它们的返回结果(如果有的话)。这样,您仍然可以知道您的课程按预期工作,并且不会测试已经彻底测试过的东西。

    你可以这样做:

    function it_stores_an_orderId(Store $session)
    {
        $store->set('testvalue')->shouldBeCalled();
        $store->get('testvalue')->shouldBeCalled()->willReturn('testvalue');
    
        $this->setCurrentOrderId('testvalue');
        $this->getCurrentOrderId()->shouldReturn('testvalue');
    
    }
    

    如果您仍想直接涉及其他一些类,Codeception 或 PHPUnit 之类的可能更合适,因为您可以更多地控制您的测试环境。

    但是,如果您仍然想使用 PHPSpec 执行此操作,则可以使用 this 包(不过我自己没有尝试过,所以不能保证)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-25
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 2014-05-29
      • 1970-01-01
      相关资源
      最近更新 更多