dou6577 2012-09-27 14:33
浏览 60
已采纳

PHPUnit测试总是成功,有$ this-> once()和$ this-> never()?

I know I'm doing something wrong because this is very strange, I'm learning PHPUnit since a few days. The test subject is receive() controller action:

class ReportController
{
    /**
     * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
     */
    private $dispatcher;

    public function __construct(EventDispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * @param \Gremo\SkebbyBundle\Message\InboudSkebbyMessage $message
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function receive(InboudSkebbyMessage $message)
    {
        $this->dispatcher->dispatch(SkebbyEvents::MESSAGE_RECEIVED,
            new InboundMessageEvent($message)
        );

        return new Response();
    }
}

As the controller throws an event, I need to mock an event subscriber (implements Symfony\Component\EventDispatcher\EventSubscriberInterface). There is a static method getSubscribedEvents(). Test method helper (to get the mock):

public function getMockSubscriber(array $events)
{
    $class = $this->getMockClass(
        'Symfony\Component\EventDispatcher\EventSubscriberInterface',
        array_merge(array_values($events), array('getSubscribedEvents'))
    );

    // Static stub method
    $class::staticExpects($this->once())
        ->method('getSubscribedEvents')
        ->will($this->returnValue($events))
    ;

    return new $class;
}

Then in my test method I'm registering the (mock) subscriber, making the request and checking that onMessageReceived() is invoked exactly one time. The (big, actually) problem is test always succeeds, even if i change the mock to $subscriber->expects($this->never())->method('onMessageReceived'). Implementation:

public function testApiCall()
{
    $client = $this->createClient();

    // Router (for route generation) and dispatcher (for subscribing the mock)
    $router    = $client->getContainer()->get('router');
    $dispatcer = $client->getContainer()->get('event_dispatcher');

    // Get mock event subscriber
    $subscriber = $this->getMockSubscriber(array(
        'messsage.received' => 'onMessageReceived'
    ));

    // Register the mock subscriber with the dispatcher
    $subscriber->expects($this->once())->method('onMessageReceived');
    $dispatcer->addSubscriber($subscriber);

    // Make the request
    $request  = Request::create(
        $router->generate('controller_receive'),
        'POST',
        array(
            'sender'    => 'sender',
            'receiver'  => 'receiver',
            'text'      => 'text',
            'timestamp' => time(),
            'smsType'   => 'smsType'
        )
    );

    $client->getKernel()->handle($request);
}

EDIT: mock subscriber is correctly registered with the dispatcher. var_dump($dispatcher->getListeners()):

array(7) {
  'messsage.received' =>
  array(1) {
    [0] =>
    array(2) {
      [0] =>
      class Mock_EventSubscriberInterface_19b191af#34 (2) {
        ...
      }
      [1] =>
      string(17) "onMessageReceived"
    }
  }
  • 写回答

1条回答 默认 最新

  • drz5553 2012-09-27 20:51
    关注

    I'd use the mocked object, instead of creating a new one from the class name:

    public function getMockSubscriber(array $events)
    {
        $subscriberMock = $this->getMock(
            'Symfony\Component\EventDispatcher\EventSubscriberInterface',
            array_merge(array_values($events), array('getSubscribedEvents'))
        );
    
        // Static stub method
        $class = get_class(subscriberMock);
        $class::staticExpects($this->once())
            ->method('getSubscribedEvents')
            ->will($this->returnValue($events))
        ;
    
        return $subscriberMock;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动