Esempio n. 1
0
        public void GetForNewItemWithMultiThread()
        {
            // SETUP
            // We will need a mock factory
            var factory = Substitute.For <IResourceLockFactory>();
            // And a controlled WaitHandle type to return
            var lockObj = Substitute.For <IResourceLock>();
            ManualResetEvent continueEvent = new ManualResetEvent(false);

            // Our factory create will wait for a control signal to return
            // while things get setup
            factory.Create().Returns((callInfo) =>
            {
                if (!continueEvent.WaitOne(TimeSpan.FromSeconds(20)))
                {
                    throw new TimeoutException("Failed to get event, not expected!");
                }
                return(lockObj);
            });
            // Create the resource lock manager
            var mgr = new ResourceLockManager <int>(factory);

            // ACT
            var t1 = Task <IResourceLock> .Factory.StartNew(() => mgr.GetFor(0));

            var t2 = Task <IResourceLock> .Factory.StartNew(() => mgr.GetFor(0));

            var t3 = Task <IResourceLock> .Factory.StartNew(() => mgr.GetFor(0));

            var t4 = Task <bool> .Factory.StartNew(() =>
            {
                Thread.Sleep(500);
                continueEvent.Set();
                return(true);
            });

            Task.WaitAll(t1, t2, t3, t4);

            // ASSERT
            // We should have gotten the item we stated to return
            Assert.AreEqual(t1.Result, lockObj);
            Assert.AreEqual(t2.Result, lockObj);
            Assert.AreEqual(t3.Result, lockObj);
            // And the factory should have been called once
            factory.Received(1).Create();
        } /* End of Function - GetForNewItemWithMultiThread */
Esempio n. 2
0
        public void GetForNewItem()
        {
            // SETUP
            // We will need a mock factory
            var factory = Substitute.For <IResourceLockFactory>();
            // And a controlled WaitHandle type to return
            var lockObj = Substitute.For <IResourceLock>();

            factory.Create().Returns(lockObj);
            // Create the resource lock manager
            var mgr = new ResourceLockManager <int>(factory);

            // ACT
            var item = mgr.GetFor(0);

            // ASSERT
            // We should have gotten the item we stated to return
            Assert.AreEqual(item, lockObj);
            // And the factory should have been called once
            factory.Received(1).Create();
        } /* End of Function - GetForNewItem */