dongnianchou7047 2016-01-15 08:29 采纳率: 0%
浏览 41
已采纳

如何构建一段时间内发生的进程的测试?

What is the approach for constructing tests of code that don't have an outcome in the immediate sense?

Let's say we have a very simple (yet quite rude) process:

  • User signs up to site
  • Two days pass
    • Send reminder email
    • Update some database fields
  • Ten days pass
    • Send "c'ya" email
    • Delete account

I can write tests for each set of sub tasks (email is sent, database is updated, etc). However how do I write well structured tests, that read something like:

"Two days after registration, reminder email should be sent" "Ten days after registration, account is deleted"

Although I am using PHP and PHPUnit, I feel the question may/may not be language agnostic.

  • 写回答

1条回答 默认 最新

  • dongyijing2353 2016-01-15 10:05
    关注

    Based on implementation of your event mechanics. Like, when some event listener somewhere in your code receives event user:reminder with user id, then you need just:

    1) Test reminder-send script by sending that event manually:

    $eventBus->init();
    $eventBus->attachListener($reminderListener);
    
    $eventBus->fire(new ReminderEvent($user->id));
    
    $this->expect(...); // reminder must be `sent` 
    

    2) Test generation of event when time had passed:

    $time = now();
    $delay = ...;
    
    $emitter = new RemindEventEmitter($user->id, $time + $delay)
    
    $eventBus->addEmitter($emitter);
    
    $eventBus->setCurrentTime($time); // when we just registered emitter...
    $eventBus->run();
    
    $this->expectNot(...); // ... that event _must not_ be fired
    
    $eventBus->setCurrentTime($time + $delay); // manually skip $delay time ...
    $eventBus->run();
    
    $this->expect(...); // test that event _must_ be fired
    

    And that event-spawning/dispatching thing ($eventBus in my example) must relay on mockable/replacable time-getter:

    // in production code
    $eventBus->setCurrentTime(now());
    
    // elsewhere in tests
    $eventBus->setCurrentTime(<point in time you want to test against>);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大