0

我正在尝试使用 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用于工匠的修补匠时,它们工作得很好。

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

如何解决这个问题?

4

1 回答 1

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 执行此操作,则可以使用软件包(虽然我自己没有尝试过,所以不能保证)。

于 2014-08-23T06:46:55.377 回答