模拟具体的FileInfo对象

4
我想模拟System.IO.FileInfo.Extension方法,并让它返回“.xls”,但我无法让任何东西起作用。
这个例子在删除方面很好用,但在扩展方面不行(代码无法编译)。请参考此示例
  [ClassInitialize]
      public static void Initialize(TestContext context)
      {
         Mock.Partial<FileInfo>().For((x) => x.Extension);
      }

我还尝试使用了这个例子,但代码是错误的。
  • 我拥有完全许可的JustMock副本
  • 我正在使用VS 2010 .net 4.0

编辑: 我知道我可以设置一个接口并以这种方式进行测试,但付费版本的JustMock应该模拟具体类。既然我已经付费购买,我想知道如何以这种方式进行操作。

3个回答

1

听起来你只需要将那个依赖项抽象成另一个包装类,这样就很容易进行模拟了。

 public class FileInfoAbstraction
 {
      protected FileInfo _fileInfo = null;

      public virtual string Extension
      {
          get { return _fileInfo.Extension; }
      }

      public FileInfoAbstraction(string path)
      {
          _fileInfo = new FileInfo(path);
      }
 }

接下来,无论您在何处使用FileInfo类,都要插入您的抽象层:

 var myFileInfo = new FileInfoAbstraction(somePath);

由于该扩展现在被标记为虚拟的,大多数模拟框架都可以修改它。


是的,我同意你的看法@Tejs,过去我也这样做过,但我被告知JustMock可以模拟具体类,并且想使用具体类。 - Micah Armantrout
也许吧,但我认为将这些硬依赖项提取到它们自己的类中会更好。此外,您可能需要采用工厂模式来从代码中删除 new 调用,以使其更适合进行单元测试。 - Tejs

1

我猜我漏掉了一个属性

[TestClass, MockClass] // **MockClass Added**
public class UnitTest1
{
        [ClassInitialize]
        public static void Init(TestContext context)
        {
             Mock.Partial<FileInfo>().For<FileInfo, string>(x => x.Extension);
        }


       [TestMethod]
       public void ShouldAssertFileInfoExtension()
       {
           var fileInfo = Mock.Create<FileInfo>(Constructor.Mocked);

           string expected = "test";

           Mock.Arrange(() => fileInfo.Extension).Returns(expected);

           Assert.AreEqual(fileInfo.Extension, expected);
       }

}

1

随着最新版本的JustMock(Q2 2012)发布,您不再需要MockClassAtriibute来模拟MsCrolib成员。

您可以按照以下方式编写上述测试:

[TestClass]
public class UnitTest1
{
        [ClassInitialize]
        public static void Init(TestContext context)
        {
            Mock.Replace<FileInfo, string>(x=> x.Extension).In<UnitTest1>();
        }


       [TestMethod]
       public void ShouldAssertFileInfoExtension()
       {
           var fileInfo = Mock.Create<FileInfo>(Constructor.Mocked);

           string expected = "test";

           Mock.Arrange(() => fileInfo.Extension).Returns(expected);

           Assert.AreEqual(fileInfo.Extension, expected);
       }
}

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