Sharepoint 使用MS Fakes时,如何应用索引?

Sharepoint 使用MS Fakes时,如何应用索引?,sharepoint,microsoft-fakes,typemock,Sharepoint,Microsoft Fakes,Typemock,我正在从TypeMock迁移到MS Fakes。在TypeMock中,我可以做这样的事情: 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

我正在从TypeMock迁移到MS Fakes。在TypeMock中,我可以做这样的事情:

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");
var fakeItem = new ShimSPListItem()
            {
                //delegates in here
            };

//some testing foo that uses the shim. Eg.
MethodUnderTest(fakeItem);
这一次,当我尝试使用以下方法检查我的值是否已设置:

Assert.AreEqual(fakeItem["someField"], expected, "Field value was not set correctly");
我最后出现了一个编译错误:

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

在SharePoint世界中,像这样的索引几乎是标准做法,我的测试代码确实做到了这一点,而且似乎没有任何问题。我的问题是为什么我不能在考试中做呢?我试着将垫片铸造到一个splistem上,但这是不允许的-我想我遗漏了一些东西。有什么想法吗?

所以我找到了答案:

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");
这不起作用-我无法使用“as”将fakeListItem转换为SPListItem。考虑一下,这是有意义的,因为垫片实际上不是从splistem派生的,而是一堆可以通过fakes框架连接到splistem的委托

这确实有效:

var fakeItem = new ShimSPListItem()
        {
            //delegates in here
        };
MethodUnderTest(fakeItem);
var item=(SPListItem) fakeListItem;
Assert.AreEqual(item["someField"], expected, "Field value was not set correctly");
大概cast允许自定义转换器运行,从而满足我们的需要

TypeMock迁移器的一个稍微容易使用的方法可能是:

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

正如您所知,创建一个垫片是为了重定向IL中的调用,而存根是一种派生类型(或实现),其中每个重写或实现都调用一个委托。您不经常需要垫片的实例,但始终需要存根的实例。小心不要使用错误的代码。谢谢@Magus-我认为在测试SharePoint内容时,我们可能会使用填隙片而不是存根,因为我们试图将测试中的代码与SharePoint API隔离开来,而SharePoint API中的大多数代码都无法存根。我理解你关于理解两者之间的区别的观点,我认为TypeMock迁移器必须明确这一点(因为TypeMock没有相同的区别),即使在大量使用垫片时,通常也不会使用实例。这是我的主要观点。你似乎在传递垫片,但它们并不是这样工作的。在ShimsContext中,您可以使用垫片来重新路由调用,而无需传递它。是的,我很欣赏您的说法,但是对于SPListItem(和其他SharePoint对象),如果不调用SharePoint平台或使用存根,我无法创建真实的实例,因为类是密封的。在这些情况下,我别无选择,只能使用一个垫片,并允许fakes框架将垫片转换为一个对象,该对象可由我的测试代码使用。