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 应该模拟具体的类。既然我付了钱,我想知道怎么做。

4

3 回答 3

1

It sounds to me like you just need to abstract that dependency into another wrapper class and then it would be easy to mock.

 public class FileInfoAbstraction
 {
      protected FileInfo _fileInfo = null;

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

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

Then, wherever you were using the FileInfo class, insert your abstraction:

 var myFileInfo = new FileInfoAbstraction(somePath);

Because the extension is marked as virtual now, most mocking frameworks will be able to modify it.

于 2012-04-16T15:55:24.133 回答
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);
       }

}
于 2012-04-18T13:02:38.150 回答
1

使用最新版本的 JustMock(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);
       }
}
于 2012-07-17T17:16:34.873 回答