c# - Unit Testing Timed Removal of Dictionary Value -


i writing in-memory cache (for lack of better term) in c#. writing cache easy part, testing another...

all of research testing classes use timers mock timer , inject class. this, new timer needs initialized each order added cache. passing timer add function solve this, classes consuming ordercache shouldn't responsible passing timer it.

i need verify that

  • the timer has been initialized
  • remove called proper order after specified duration
  • the order updated in dictionary , no timer created when adding same order twice

    private readonly dictionary<int, order> _orders;  private timespan _cacheduration;  public ordercache(timespan cacheduration) {     _cacheduration = cacheduration;     _orders = new dictionary<int, order>(); }  public void add(order order) {     var cachedorder = getorderbyid(order.id);     if (cachedorder == null)     {         _orders.add(order.id, order);         var timer = new timer(_cacheduration.totalmilliseconds);         timer.elapsed += (sender, args) => remove(order.id);     }     else     {         _orders[order.id] = order;     } }  public order getorderbyid(int orderid) {     return _orders.containskey(orderid) ? _orders[orderid] : null; }  public void remove(int orderid) {     if (_orders.containskey(orderid))     {         _orders.remove(orderid);     } } 

a: timer has been initialized

q: should avoid white-box testing, because if internal implementation changed, not behavior, interface or contract, should rewrite test again.

a: remove called proper order after specified duration

q: can write test:

[test] void should_remove_...() {     mocktimer timer = new mocktimer();          mycache cache = new mycache(timer);     datetime expiredat = datetime.now.add(..);     cache.add("key", "value", expiredat);      timer.settime(expiredat);      assert.that(cache, is.empty) } 

ps: recommend use http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx


Comments