Question

I'm in the process for migrating from TypeMock to MS Fakes. In TypeMock I can do stuff like this:

var fakeItem = Isolate.Fake.Instance<SPListItem>();

//some testing foo that uses the fake item Eg.
MethodUnderTest(fakeItem);

Assert.AreEqual(fakeItem["someField"], expected, "Field value was not set correctly");

In my assert I can retrieve the field value that's been set by my testing foo and compare that with my expectations.

When using MS Fakes, I'll do something like this:

var fakeItem = new ShimSPListItem()
            {
                //delegates in here
            };

//some testing foo that uses the shim. Eg.
MethodUnderTest(fakeItem);

This time when I try to check that my value has been set using:

Assert.AreEqual(fakeItem["someField"], expected, "Field value was not set correctly");

I end up with a compile error:

Cannot apply indexing with [] to an expression of type 'Microsoft.SharePoint.Fakes.ShimSPListItem'  

In the SharePoint world indexing like this is pretty much standard practice and my code under test certainly does it and seems to work without any issues. My question is why can't I do it in my test? I've tried casting the shim to an SPListItem but it's not allowed - I guess I'm missing something here. Any ideas?

Was it helpful?

Solution

So I've found the answer:

var fakeItem = new ShimSPListItem()
        {
            //delegates in here
        };
MethodUnderTest(fakeItem);
var item=fakeListItem as SPListItem;
Assert.AreEqual(item["someField"], expected, "Field value was not set correctly");

This doesn't work - I can't convert fakeListItem to an SPListItem using 'as'. Thinking about it this makes sense since the shim isn't actually derived from an SPListItem instead it's a pile of delegates that can be hooked up to an SPListTem by the fakes framework.

This does work:

var fakeItem = new ShimSPListItem()
        {
            //delegates in here
        };
MethodUnderTest(fakeItem);
var item=(SPListItem) fakeListItem;
Assert.AreEqual(item["someField"], expected, "Field value was not set correctly");

Presumably the cast allows a custom converter to run giving us what we need.

A slightly easier to work with for TypeMock migrators might be:

SPListItem fakeItem = new ShimSPListItem()
        {
            //delegates in here
        };
MethodUnderTest(fakeItem);
Assert.AreEqual(fakeListItem["someField"], expected, "Field value was not set correctly");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top