【发布时间】:2016-07-21 17:47:28
【问题描述】:
我有以下测试用例:
private static readonlystring TEST_KEY = "SomeKey";
private static readonly object TEST_VALUE = 2;
private static readonlyTimeSpan TEST_EXPIRATION = TimeSpan.FromSeconds(2);
[TestMethod]
public void SetMethodStoresValueForCorrectTime()
{
Mock<ObjectCache> mock = new Mock<ObjectCache>();
// Setup mock's Set method
mock.Setup(m => m.Set(TEST_KEY, TEST_VALUE, It.IsAny<DateTimeOffset>(), It.IsAny<string>()))
.Callback(() => mock.Setup(m => m.Get(TEST_KEY, It.IsAny<string>())).Returns(TEST_VALUE));
MyCache<object> instance = new MyCache<object>(mock.Object);
// Add value to mocked cache
instance.Set(TEST_KEY, TEST_VALUE, TEST_EXPIRATION);
Assert.AreEqual(TEST_VALUE, instance.Get(TEST_KEY));
// Configure a timer for item's expiration (Make mock's Get method return null)
Timer timer = new Timer(_ => mock.Setup(m => m.Get(TEST_KEY, It.IsAny<string>())).Returns(null), null, TEST_EXPIRATION.Milliseconds, -1);
// Wait for TimerCallback to trigger
Thread.Sleep(TEST_EXPIRATION.Add(TimeSpan.FromSeconds(1)));
Assert.IsNull(instance.Get(TEST_KEY)); // <-- Failing here
timer.Dispose();
}
这里是MyCache<T>(它的相关部分):
public class MyCache<TSource> : ICache<TSource>
{
private ObjectCache _innerCache;
public MyCache(System.Runtime.Caching.ObjectCache innerCache)
{
_innerCache = innerCache;
}
// ...
public TSource Get(string key)
{
if (key == null) throw new ArgumentNullException("key");
object value = _innerCache.Get(key);
return value != null ? (TSource)value : default(TSource);
}
public void Set(string key, TSource value, TimeSpan expiration)
{
if (key == null) throw new ArgumentNullException("key");
_innerCache.Set(key, value, DateTimeOffset.UtcNow.Add(expiration));
}
}
为什么测试失败了? 最后一个断言失败了:
Assert.IsNull 失败。
我在这里做错了吗?
【问题讨论】:
-
你为什么要创建一个计时器而不使用它(除了丢弃它)?
-
@JeroenHeier 它应该在
TEST_EXPIRATION.Milliseconds毫秒后自动启动
标签: c# multithreading unit-testing moq mstest