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
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Hallo,

I need to test some lgacy code. I have more or less the following code:

        
public void DoSomething()
        {
            var tabitem = new XTabItem() { Header = "ASF" };

            XYZ(tabitem);
        }

        public void XYZ(ITabItem tabitem)
        {
            Console.Write(tabitem.Header);
        }

XTabItem has the base class TabItem and inherit from ITabItem.

I have the following test code:
        
[Test]
        public void TestMethod()
        {
            var class1 = new Class1();
            Isolate.WhenCalled(() => Console.Write("")).IgnoreCall();
            Isolate.Swap.AllInstances<XTabItem>().WithRecursiveFake();

            class1.DoSomething();

            Isolate.Verify.WasCalledWithExactArguments(() => Console.Write("ASF"));
        }


If the parameter of "XYZ" would be type of XTabItem everything works great. If its ITabItem (as the production code) header will be "reseted" to null. Is there a problem with typemock or do I have to change something?

Thanks for help,

Moritz
asked by Moritz (18.3k points)

1 Answer

0 votes
Hi,

In order to fake an instance of class which implements an interface you ought to use Fake.NextInstance like this :
        [TestMethod]
        [Isolated]
        public void TestMethod()
        {
            var class1 = new Class1();
            Isolate.WhenCalled(() => class1.OtherConsole(null)).IgnoreCall();
            var fake = Isolate.Fake.NextInstance<XTabItem>();
            class1.DoSomething();
            Isolate.Verify.WasCalledWithExactArguments(() => class1.OtherConsole("ASF"));
        }
    }

Fake.NextInstance lets you fake a future instance of concrete class or some interface this class implements.
Notice that var fake = Isolate.Fake.NextInstance<ITabItem>(); also works.

Second thing, we currently don't support faking mscorlib, it means trying to fake
Console's method call directly is impossible.
I can add this to our features list by request.

To workaround this problem i wrapped the Console.Writeline like this :
public class Class1
    {
        public void DoSomething()
        {
            var tabitem = new XTabItem() {Header = "ASF"};
            XYZ(tabitem);
        }
        public void XYZ(XTabItem tabitem)
        {
            OtherConsole(tabitem.Header);
        }
        public void OtherConsole(string msg)
        {
            Console.Write(msg)
        }
    }


Let me know if that helped you.
answered by Shai Barak (1.5k points)
...