Mock FileStream?

2 posts, 0 answers
  1. Rayne
    Rayne avatar
    254 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
    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

          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");
              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:

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

    Kind Regards
    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

Back to Top