Thursday, January 17, 2013

MoQ - Running tests in Parallel

It may not be accurate to say that MoQ (Quick start intro) is thread safe when running tests in parallel because it appears it is not in other circumstances.  Check out this blog post where they modified the source to fix a threading issue.

However, it appears that MoQ avoids the issue I described in the previous post about how Rhino falls over intermittently when running tests in parallel.  MoQ avoids this by design.  Here's the modified code from  Test1 converted to MoQ:


    [TestClass]
    public class Test1
    {
        [TestMethod]
        public void Test1a()
        {
            var dependency1 = new Mock<IDependency1>();
            var dependency2 = new Mock<IDependency2>();

            dependency1.Setup(m => m.DependentMethod("System.String")).Returns(false);

            dependency2.Setup(m => m.Kind).Returns(TypeKind.Foo);
            dependency2.Setup(m => m.StringProperty).Returns("System.String");

            var target = new TestSubject(dependency1.Object, dependency2.Object);
            Assert.IsFalse(target.SubjectMethod());
            dependency1.VerifyAll();
            dependency2.VerifyAll();
        }

        [TestMethod]
        public void Test1b()
        {
            var dependency1 = new Mock<IDependency1>();
            var dependency2 = new Mock<IDependency2>();

            dependency1.Setup(m => m.DependentMethod("System.String")).Returns(true);

            dependency2.Setup(m => m.Kind).Returns(TypeKind.Foo);
            dependency2.Setup(m => m.StringProperty).Returns("System.String");

            var target = new TestSubject(dependency1.Object, dependency2.Object);
            Assert.IsTrue(target.SubjectMethod());
            dependency1.VerifyAll();
            dependency2.VerifyAll();
        }
   }

These tests pass every time.
Even the updated brute force parallel tests runs ok.
    [TestClass]
    public class Test2
    {
        [TestMethod]
        public void BruteForceTest()
        {
            var threads = new Thread[30];
            for (int i = 0; i < threads.GetUpperBound(0); i++)
            {
                threads[i] = new Thread(this.ThreadAction);
                threads[i].Start();
            }

            for (int i = 0; i < threads.GetUpperBound(0); i++)
            {
                threads[i].Join();
            }
        }

        private void ThreadAction()
        {
            var dependency1 = new Mock<IDependency1>();
            var dependency2 = new Mock<IDependency2>();

            dependency1.Setup(m => m.DependentMethod("System.String")).Returns(false);

            dependency2.Setup(m => m.Kind).Returns(TypeKind.Foo);
            dependency2.Setup(m => m.StringProperty).Returns("System.String");

            var target = new TestSubject(dependency1.Object, dependency2.Object);
            target.SubjectMethod();
        }
    }


No comments:

Post a Comment