Mocking System.Enum

2 posts, 0 answers
  1. Christian
    Christian avatar
    5 posts
    Member since:
    Apr 2013

    Posted 23 Jul 2013 Link to this post

    I try to create a mock for System.Enum. That works for all public static methods of the System.Enum class (i.e. Enum.GetValues). But I have no idea how to set up the mock for the ToString() method of the Enum object.
    (all C# .NET)

    public static void TestThis(ListControl ctrl, Type enumType, Enum enumItem= null)
        int[] itemValues = Enum.GetValues(enumType).ToArray<int>();
        string[] itemNames = Enum.GetNames(enumType);
        string s = enumItem.ToString();

    Mock.SetupStatic(typeof(Enum), Behavior.Strict);
    Mock.Arrange(() => Enum.GetValues(Arg.IsAny<Type>())).Returns(new int[] { 1, 2, 3 });
    Mock.Arrange(() => Enum.GetNames(Arg.IsAny<Type>())).Returns(new string[] { "1", "2", "3" });
    //--- this causes an exception (Cannot create mock for type due to CLR limitations.)
    Enum e = Mock.Create<Enum>();
    Mock.Arrange(() => e.ToString()).IgnoreArguments().IgnoreInstance().Returns("2");

    //--- in that case null is returned instead of "2"; compiler never steps into the mocked "returns"
    TestEnum e = Mock.Create<TestEnum>();
    Mock.Arrange(() => e.ToString()).IgnoreArguments().IgnoreInstance().Returns("2");

    DropDownList ddlTestList = new DropDownList();
    TestThis(ddlTestList, typeof(TestEnum), TestEnum.Empty)
  2. Stefan
    Stefan avatar
    198 posts

    Posted 24 Jul 2013 Link to this post

    Hi Christian,

    It's simply impossible to arrange the instance methods of System.ValueType and System.Enum. Like the exception says, it's a limitation of the CLR.

    As a rule of thumb, if you need to mock Enum.ToString(), you might want to reconsider what is it that you're doing... because you might be doing something that you will eventually hate to provide support for.

    Share what you think about JustTrace & JustMock with us, so we can become even better! You can use the built-in feedback tool inside JustTrace, our forums, or our JustTrace or JustMock portals.
Back to Top