.NET方法不会生成Shims

16

当我开始使用Microsoft Fakes时,我很兴奋地开始对一些.NET方法进行振铃。我被告知我可以振铃任何.NET方法(静态或非静态):http://msdn.microsoft.com/en-us/library/hh549176.aspx

然而,我一直在尝试振铃TcpClient中的一些方法,但只创建了存根,这对我没有任何好处,因为我希望能够更改其中一些方法,使其返回我的数据而不是依赖活动的TcpClient给我数据。

如果除了Microsoft Fakes还有其他方法,请提出建议。

编辑:添加代码以演示问题

[TestMethod]
public void CommunicationTest()
{
    var stubbedTcpClient = new System.Net.Sockets.Fakes.StubTcpClient
    {

    };

    //No such ShimTcpClient exists
    var shimmedTcpClient = new System.Net.Sockets.Fakes.ShimTcpClient
    {

    };
}

我添加了TcpClient的桥接代码,希望能够生成。 - David J
你正在尝试使用什么方法?如果它是虚拟方法,你可以使用NSubstitute,否则你只能使用Fakes。 - Ryan Gates
可用的 Available 和连接的 Connected 属性以及 GetStream 方法。我会给 NSubstitute 一次机会,看看会发生什么。我仍然想得到一个坚实的理由,为什么我似乎无法获得任何 .NET 类的生成摇身变形版本,除了 DateTime 外。 - David J
如果方法既不是虚拟的也不是接口(GetStream() 都不是),那么您将无法使用 NSubstitute。 - Ryan Gates
是的,我刚查了一下。NSub看起来与Moq非常相似。不过还是谢谢你的建议。 - David J
显示剩余2条评论
2个回答

10

这篇博客文章这里的帮助下,我解决了这个问题。

解决方案是在System.fakes文件中明确添加我想要的shim类。我的文件现在看起来像这样:

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="System" Version="4.0.0.0"/>
  <ShimGeneration>
    <Clear/>
    <Add FullName="System.Net.Sockets.TcpClient"/>
    <Remove Obsolete="1"/>
  </ShimGeneration>
</Fakes>

Remove Obsolete="1"是为了防止Shim生成代码在尝试用Shim处理[Obsolete]代码时抛出错误。


1
I also had the same problem. 我的System.fakes和mscorlib.fakes看起来像这样:
<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="mscorlib" Version="4.0.0.0"/>
  <ShimGeneration>
    <Add Namespace="System.ComponentModel.BackgroundWorker"/>
  </ShimGeneration>
</Fakes>

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="System" Version="4.0.0.0"/>
  <ShimGeneration>
    <Add Namespace="System.ComponentModel.BackgroundWorker"/>
  </ShimGeneration>
</Fakes>

解决方案

System.fakes

 <Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
   <Assembly Name="System" Version="4.0.0.0"/>
   <ShimGeneration>
     <Add FullName="System.ComponentModel.BackgroundWorker!"/>
   </ShimGeneration>
 </Fakes>

mscorlib.fakes

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="mscorlib" Version="4.0.0.0"/>
  <ShimGeneration>
    <Add FullName="System.ComponentModel.BackgroundWorker!"/>
  </ShimGeneration>
</Fakes>

保存文件后,我重新构建了解决方案。现在我有了ShimBackgroundWorker。


我正在使用VS.Net Ultimate 2012。 - Fery
我已经按照以下方式更改了文件,现在我有了ShimBackgroundWorker。 - Fery
1
重要提示:FullName末尾的感叹号是可选的。如果没有它,Fakes代码生成器将考虑所有以指定字符串开头的类型。感叹号告诉代码生成器寻找精确匹配。 - Gabriel Bourgault
这对我们使用System.Net.WebClient有效,记得重新构建解决方案! - DrLime2k10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接