This is a migrated thread and some comments may be shown as answers.

Mocking System.Enum

1 Answer 1748 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Christian
Top achievements
Rank 1
Christian asked on 23 Jul 2013, 01:45 PM
hello,
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)

method:
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:
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)

1 Answer, 1 is accepted

Sort by
0
Stefan
Telerik team
answered on 24 Jul 2013, 08:25 AM
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.

Regards,
Stefan
Telerik
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.
Tags
General Discussions
Asked by
Christian
Top achievements
Rank 1
Answers by
Stefan
Telerik team
Share this question
or