【发布时间】:2018-06-26 21:59:29
【问题描述】:
我有一个启动计时器的模拟对象,需要在我的测试中处理掉。处理模拟对象的正确方法是什么?在我要被嘲笑的课堂上,我有:
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Stop and dispose timer here.
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
}
所以现在在我的测试中,我需要模拟对象,使用它,然后确保它被处理掉。我知道我可以设置CallBase = true,但我不确定这是否是正确的(行业标准)做事方式:
[TestMethod]
public void TestSomething()
{
var mock = new Mock<ObjectWithTimer>() { CallBase = true };
using (var foo = mock.Object)
{
foo.DoSomething(); // This consequently starts a timer.
} // Here, Dispose() will be called.
}
当 using 块结束时,Dispose() 被调用,它调用基类Dispose(bool)。但是,是否可以在不向我的模拟中添加 CallBase = true 的情况下进行此处理?当我需要模拟来覆盖其他方法时,这并不理想。
【问题讨论】:
-
再次阅读您的帖子,我不太确定您是想测试另一个使用 ObjectWithTimer 的类,还是 ObjectWithTimer 类本身?
-
嗨,Desty。在这种情况下,我想测试 ObjectWithTimer 类本身。
-
我还没弄明白,如果要测试ObjectWithTimer类,为什么要mock呢?
标签: c# .net unit-testing mocking moq