Mock FileStream?

4 posts, 0 answers
  1. Rayne
    Rayne avatar
    261 posts
    Member since:
    Sep 2010

    Posted 19 Oct 2012 Link to this post

    I'm new to JustMock and Unit Testing in general.

    I have a method WriteToDisk(object param) that creates a new FileStream, calls FileStream.Write, then sets a bool property in the class to true. I'd like to test that the property is set to true (if no exceptions are thrown) without actually writing to disk.

    I'm just not sure how to arrange things in my test to bypass the Filestream instance and the call to FileStream.Write. Can this even be done with JM?
  2. Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 23 Oct 2012 Link to this post

    Hi Rayne,
    Thanks again for contacting us.

    Yes it is possible to mock FileStream using JustMock. Here is one example that writes fake content using FileStream.Write

             [TestMethod]
          public void ShouldMockFileOpenWithCustomFileStream()
          {
              byte[] actual = new byte[255];
     
              // writing locally, can be done from resource manifest as well.
     
              using (StreamWriter writer = new StreamWriter(new MemoryStream(actual)))
              {
                  writer.WriteLine("Hello world");
                  writer.Flush();
              }
              
              FileStream fs = Mock.Create<FileStream>(Constructor.Mocked); 
     
              // mocking the specific call and setting up expectations.
              Mock.Arrange(() => fs.Write(null, 0, 0)).IgnoreArguments()
                  .DoInstead((byte[] content, int offset, int len) => actual.CopyTo(content, offset));
     
              // return custom filestream for File.Open.
              Mock.Arrange(() => File.Open(Arg.AnyString, Arg.IsAny<FileMode>())).Returns(fs);
     
     
              // act
              var fileStream =  File.Open("hello.txt", FileMode.Open);
              byte[] fakeContent = new byte[actual.Length];
     
              // original task
              fileStream.Write(fakeContent, 0, actual.Length);
     
              // assert
              Assert.Equal(fakeContent.Length, actual.Length);
     
              for (var i = 0; i < fakeContent.Length; i++)
              {
                  Assert.Equal(fakeContent[i], actual[i]);
              }
          }

    FileStream however is an mscorlib. Therefore, you first have to initialize it in the following way:

     

    Mock.Replace<FileStream, byte[], int, int>((x, i, j, k) => x.Write(i, j, k)).In<MsCorlibFixture>(x => x.ShouldMockFileOpenWithCustomFileStream());

    Mock.Replace<string, FileMode>((i, j) => File.Open(i, j)).In<MsCorlibFixture>(x => x.ShouldMockFileOpenWithCustomFileStream());

    Since, I mocked File.Open, therefore initialized it here as well. More detail on mscorlib initialization can be found here:

    http://www.telerik.com/help/justmock/advanced-usage-mscorlib-mocking.html

    Hope this gets you started on mocking and JustMock and should have other questions please don't hesitate to contact us.


    Kind Regards
    Mehfuz
    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

  3. Manish
    Manish avatar
    1 posts
    Member since:
    Feb 2021

    Posted 12 Feb in reply to Ricky Link to this post

    Hi Mehfuz,

    I have gone through the code what you have suggested, but it is throwing  exception as :

    Telerik.JustMock.Core.ElevatedMockingException: 'Cannot mock 'System.IO.File'. JustMock Lite can only mock interface members, virtual/abstract members in non-sealed classes, delegates and all members on classes derived from MarshalByRefObject on instances created with Mock.Create or Mock.CreateLike. For any other scenario you need to use the full version of JustMock.'

  4. Ivo
    Admin
    Ivo avatar
    40 posts

    Posted 12 Feb Link to this post

    Hello Manish,

    In order to be able to mock objects from mscorlib (and System.IO.File in particular) you have to enable profiler (a.k.a. as "elevated mocking" or "advanced mode") in prior, please check the currently selected option in the JustMock extension menu, it should be like this one below:

    I hope this information helps. If you need further assistance do not hesitate to write us again.

    Regards,
    Ivo
    Progress Telerik

    Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Back to Top