簡體   English   中英

單元測試同步代碼是否具有競爭條件?

[英]Unit Test Synchronous Code has a Race Condition?

我已經在git hub上上傳了一些代碼,可以在這里找到: https : //github.com/Shaunus87/SyncTest ,其中包括我的原型代碼和我的單元測試。

我實質上是聲明我的同步代碼,連接一個事件,調用一個將最終調用該事件的方法,並斷言該事件是否被調用:

        bool called = false;

        var testBinsToVend = GetRoboBins();
        var vendHelper = new VendingHelper(null, testBinsToVend, VendType.Issue);

        vendHelper.Complete += delegate () {
            called = true;
        };

        vendHelper.DoVending();

        Assert.IsTrue(called);

所有代碼都是同步的(據我所知),但是,如果我運行測試,它將失敗,如果對它進行調試,則可以通過...

我已經嘗試了一些方法,似乎要么a)我的代碼是秘密異步的並且有競爭條件,要么b)運行代碼時它決定不執行一半事件?

我勒個去?

編輯:我也試圖設置手動重置事件,如下所示:

        bool called = false;
        var done = new ManualResetEvent(false);

        var testBinsToVend = GetRoboBins();
        var vendHelper = new VendingHelper(null, testBinsToVend, VendType.Issue);

        vendHelper.Complete += delegate () {
            called = true;
            done.Set();
        };

        vendHelper.DoVending();

        done.WaitOne();
        Assert.IsTrue(called);
        //was complete called?
        Assert.AreEqual(true, vendHelper.Bins.All(x => x.State != VendState.Pending));

但是由於這是執行的一行, done.WaitOne(); 被擊中,測試永遠不會到達Assert.IsTrue(called); 線。

您的業​​務邏輯中存在一個問題:

private CommCommand GetLastCommand(List<CommCommand> cmds, DateTime since) {
 return cmds.Where(x => x.DateTime > since)
            .OrderByDescending(x => x.DateTime)
            .FirstOrDefault();
}

DateTime.Now默認情況下只有約20ms左右的分辨率。 這意味着您的消息早在DateTime > since之前DateTime > since收到, DateTime > since這是正確的。 當您單步執行代碼時,會調整時間-原始接收后, Send發生的時間會更長。

您不能依賴DateTime.Now進行消息排序。 它根本不夠准確。 如果您確實認為可以依靠發送和接收的順序進行排序(也就是說,計算機在得到提示之前從不答復),請改為使用簡單的計數器來代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM