簡體   English   中英

使用Moq進行單元測試並行功能

[英]Unit testing parallel function using moq

我有基本的接口,還有一個在構造函數中實現該接口的類,然后根據輸入順序地或並行地獲取一些數據。

    public interface ISomeService
    {
        List<int> FetchSomeData(int a);
    }      

    public class SomeClass
    {
        private ISomeService sr { get; }

        public SomeClass(ISomeService sr) => this.sr = sr;

        public int DoMagic(bool paralell)
        {
            int sum = 0;
            if (paralell)
            {
                Parallel.For(0, 10, (x) =>
                {
                    sum += sr.FetchSomeData(x).Sum(z => z);
                });
            }
            else
            {
                for (int i = 0; i < 10; i++)
                {
                    sum += sr.FetchSomeData(i).Sum(z => z);
                }
            }
            return sum;
        }
    }

然后我進行了測試:

    [Test]
    public void DoTest()
    {

        var service = new Mock<ISomeService>(MockBehavior.Strict);
        service.Setup(x => x.FetchSomeData(It.IsAny<int>()))
            .Returns(() => new List<int> { 3 });

        var someClass = new SomeClass(service.Object);

        var notParallel = someClass.DoMagic(false);

        var parallel = someClass.DoMagic(true);

        Assert.AreEqual(30, notParallel);

        Assert.AreEqual(30, parallel);
    }

和問題:

NotParallel的結果總是相同的(30),但是在並行情況下,結果卻有所不同(有時為15,其他時間為21等)。 可能是什么問題? 如何解決呢?

您正在從多個線程更新變量sum。 以下是一些使此線程安全的方法: https : //social.msdn.microsoft.com/Forums/vstudio/en-US/d87c1085-cacb-4d82-826f-4151bf967f86/parallelfor-with-sum?forum=並行擴展

暫無
暫無

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

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