我有一个 DispatcherTimer,我会在该计时器的计时器滴答中检查组件的忙碌/空闲状态。我必须等到组件空闲,比如 IsBusy() 方法返回 false,然后我必须自动启动一些东西。我想通过首先模拟组件繁忙然后在一段时间后使其空闲并查看自动功能启动来测试场景。当然,一旦我调用被测代码,我就会进入等待状态。是否可以从测试中设置新的期望并将更新发送到生产代码,以便我可以做我需要做的事情?我正在使用 Nunit 进行单元测试。
最佳答案
您可以使用 Rhino Mocks 的 Do() Handler
在 IsBusy()
中模拟预先指定的等待时间被模拟的组件的方法:
[TestFixture]
public class TestClass
{
[Test]
public void MyTest()
{
var mocks = new MockRepository();
var mockComponent = mocks.DynamicMock<MyComponent>();
using (mocks.Record ())
{
Expect.Call(() => mockComponent.IsBusy())
.Do((Func<bool>)(() =>
{
System.Threading.Thread.Sleep(10000); // wait 10 seconds
return false;
}));
// perhaps define other expectations or asserts here...
}
using (mocks.Playback())
{
var classUnderTest = new ClassUnderTest(mockComponent);
classUnderTest.MethodUnderTest();
}
mocks.VerifyAll();
}
}
然后您可以根据需要通过多个单元测试或使用 NUnit's Parameterized Tests 来测试不同的 sleep 时间。 (我只是随意选择等待 10 秒)。
ClassUnderTest.MethodUnderTest()
应该调用 MyComponent.IsBusy()
在其实现的某个时刻,直接或间接通过 Tick
DispatcherTimer
的事件处理程序你提到。没有看到你的代码,我猜你可能有类似这样的东西:
public class ClassUnderTest
{
private MyComponent myComponent;
public ClassUnderTest(MyComponent myComponent)
{
this.myComponent = myComponent;
}
public void MethodUnderTest()
{
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();
// ...
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
if(!myComponent.IsBusy())
{
// do something else now...
}
}
}
public class MyComponent
{
public virtual bool IsBusy()
{
// some implementation that will be faked via the Do Handler
return false;
}
}
关于c# - 在单个方法调用中改变对犀牛模拟的期望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7495755/