tags:

views:

49

answers:

1

I'm getting the exception

The type initializer for 'Moq.Mock`1' threw an exception.

using Moq 4.0 I've checked around on a couple of forums and they allude to using the Moq-NoCastle version. I've tried both this and version in the Moq folder. Both with the same result.

I've got a solution with 2 projects, one for my interface, one for my tests. My main project has 2 files:

IMyInterface.cs:

using System;

namespace Prototype
{
    public interface IMyInterface
    {
        int Value { get; set; }
        void ProcessValue();
        int GetValue();
    }
}

My program.cs file has just the default code that's generated with the project.

My test project has a single file for my dummy test - TestProgram.cs

using System;
using NUnit.Framework;
using Moq;

namespace Prototype.UnitTests
{
    [TestFixture]
    public class TestProgram
    {
        Mock<IMyInterface> mock;

        [TestFixtureSetUp]
        void TestSetup()
        {
            mock = new Mock<IMyInterface>();
            mock.Setup(x => x.GetValue()).Returns(2);
        }

        [Test]
        public void RunTest()
        {
            IMyInterface obj = mock.Object; /* This line fails */
            int val = obj.GetValue();
            Assert.True(val == 2);
        }
    }
}

According to the documentation all is good and proper, and it compiles nicely. The problem comes when I try to run the test. It gets to the line marked above and crashes with the exception:

The type initializer for 'Moq.Mock`1' threw an exception.

I can't see what's going wrong here, can anyone shed some light on it?

+3  A: 

I was able to run your test successfully after making the following changes:

  1. Made TestSetup() public
  2. In RunTest, changed int val = obj.Value to int val = obj.GetValue() - this was just to get the Assert to pass.

I'm not familiar with NUnit (I use xUnit), but my guess is TestSetup() being private was the problem. When that method is private, NUnit shows this exception for me:

Prototype.UnitTests.TestProgram.RunTest:
Invalid signature for SetUp or TearDown method: TestSetup

Maybe you are using an older version of NUnit that handled this situation differently (I just downloaded 2.5.7.10213).

HTH

adrift
Thanks. It looks like the 'public' accessor needed to be set on the setup. What I couldn't figure out was when I used the debugger to debug the test, it actually ran through that method. So my assumption was that it didn't need to be public.
BenAlabaster
You're welcome. Sounds like NUnit was behaving strangely, and not giving good feedback.
adrift