Domanda

Hi all,

I have a class "Abc", in which I have some read only property (Context). In constructor of "Abc" class I am setting value to read only property using a private variable (_context). e.g Abc() {_context=new Xyz();}

I want to create a test case using TypeMock, in which I want to mock Xyz class and return value to _context. So that I can fill context using some fake data.

Kindly let me know is it possible to mock class with values. Thanks

È stato utile?

Soluzione

What you want to look at is the "Swap" functionality of Isolator.

// First set up your fake Xyz.
var fakeXyz = Isolate.Fake.Instance<Xyz>();
Isolate.WhenCalled(() => fakeXyz.SomeMethod()).WillReturn("Value");

// Now tell Isolator that the next time someone does
// "new Xyz()" you want it to be your fake.
Isolate.Swap.NextInstance<Xyz>().With(fakeXyz);

// Create your Abc and do your assertions. This should pass:
var realAbc = new Abc();
Assert.AreEqual("Value", realAbc.Context.SomeMethod();

A good reference for figuring out this sort of basic Isolator functionality is the online documentation on the Typemock site. Check out the "Quick Start" and the "Using Typemock Isolator" sections. There are plenty more examples to show you how to do similar and more advanced things.

UPDATE: I previously showed Assert.AreSame(fakeXyz, realAbc.Context) as the way to verify the swap took place. It appears that in some versions of Typemock the Assert.AreSame will fail because there is some sort of dynamic proxy mechanism at work - they aren't actually swapping in for literally the same instance of the fake, they're doing some trickery to get things to happen. However, the calls on the fake instance will still be called and you'll still get the expected result. I've updated the sample snippet accordingly.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top