質問

I would like to Mock the System.IO.FileInfo.Extension Method and have it return ".xls" but I can't get anything to work

This Example works great for Delete but not for Extension (The code will not compile)

  [ClassInitialize]
      public static void Initialize(TestContext context)
      {
         Mock.Partial<FileInfo>().For((x) => x.Extension);
      }

I Have also tried using this example but the code is wrong.

  • I have a fully licensed copy of JustMock
  • I am using VS 2010 .net 4.0

Edit: I know I can setup a interface and test that way, but the paid version JustMock is supposed to mock concrete classes. Since I paid for it, I would like to know how to do it that way.

役に立ちましたか?

解決

With the latest release of JustMock (Q2 2012). You no longer need the MockClassAtriibute for mocking MsCrolib members.

You can write above test very much in the following way:

[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);
       }
}

他のヒント

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.

Guess I was missing an attribute

[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);
       }

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top