c# - 在单个方法调用中改变对犀牛模拟的期望

标签 c# .net rhino-mocks

我有一个 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/

相关文章:

c# - 如何遍历 json 对象中的项目并在 C# 中检索特定值?

c# - 将 mashape api 响应转换为 c# 类

C# 改变文本框中一个字符的颜色

c# - MS Office Interop - 无法发布对 RCW 的引用

mocking - 有没有办法决定 RhinoMocks 模拟何时开始录制?

c# - Blazor 编译器如何生成序列号?

c# - 通过 C# 在 Excel 中打开 CSV 文件?

c# - Rhinomock 期望中的非原始对象

c# - 如何模拟字典?

c# - 给定坐标,我如何获得 10 英里半径内的所有邮政编码?