chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
+1 vote

Hi all,

There is a class (StaticStuff) that I am not mocking. However, TypeMock prevents .NET from initializing the class's static data (SomethingStatic) when it appears in another class that I am mocking (ClassToMock).

There are other discussions on the matter:

I am on version 8.6.0.

I am familiar with the workaround of referencing SomethingStatic before mocking ClassToMock. I am, instead, inquiring into a fix of the root cause.

Thank you!

Chris V


using Microsoft.VisualStudio.TestTools.UnitTesting;
using TypeMock.ArrangeActAssert;

namespace TypeMockStatic
{
    [TestClass]
    public class TypeMockStaticDemo
    {
        [TestMethod]
        public void TypeMockStaticDemo_Part1()
        {
            ClassToMock mockedClassToMock = Isolate.Fake.Instance<ClassToMock>();
            Isolate.WhenCalled(() => mockedClassToMock.GetSomethingStatic()).CallOriginal();

            string somethingStatic = mockedClassToMock.GetSomethingStatic();

            Assert.AreEqual("Something Static", somethingStatic);
        }
    }

    public class ClassToMock
    {
        public string GetSomethingStatic()
        {
            return StaticStuff.SomethingStatic;
        }
    }

    public class StaticStuff
    {
        public static string SomethingStatic = "Something Static";
    }
}

asked by chrisv (1.1k points)

FYI, here is a clarification of my comment, "I am familiar with the workaround of referencing SomethingStatic before mocking ClassToMock."

Here is the code for the workaround. All I did was add the line that creates somethingStaticWorkaround, making sure it comes before mocking ClassToMock.

Notice that I don't use that variable. What's the purpose, then? The purpose is to force the initialization of StaticStuff's static data. If I do this, then the test passes.

- Chris V


        [TestMethod]
        public void TypeMockStaticDemo_Part1()
        {
            string somethingStaticWorkaround = StaticStuff.SomethingStatic;

            ClassToMock mockedClassToMock = Isolate.Fake.Instance<ClassToMock>();
            Isolate.WhenCalled(() => mockedClassToMock.GetSomethingStatic()).CallOriginal();

            string somethingStatic = mockedClassToMock.GetSomethingStatic();

            Assert.AreEqual("Something Static", somethingStatic);
        }

Please log in or register to answer this question.

...