DevLabs > DevLabs Forums > Pex > Mocking Stream.Read using moles?
Ask a questionAsk a question
 

AnswerMocking Stream.Read using moles?

  • Wednesday, October 28, 2009 2:16 PMArul Prasad Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    I need to unit test the following method . I need to mock the stream object . When I use MStream ,

     

    MStream a = new MStream();

    a.ReadByte = () => ;

     

    Test is failing since MStream() object cannot be created as it is abstract class (object creation is not possible). I tried assigning MFileStream Object to it but type doesn’t allow . Is there a way to mock this stream.Read?

     

        public static bool IsAssemblyDownloaded(string assemblyFile, Stream stream)

            {

                bool status = false;

                using (var file = new FileStream(assemblyFile, FileMode.Create, FileAccess.ReadWrite))

                {

                    var buffer = new byte[ConstMaxBufferSize];

                    if (buffer.Length > 0)

                    {

                        int count;

                        while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)

                        {

                            file.Write(buffer, 0, count);

                            file.Flush();

                        }

     

                        stream.Close();

                        file.Position = 0;

                        status = true;

                    }

                }

     

                return status;

            }

    •  

Answers

  • Wednesday, October 28, 2009 2:48 PMPeliMSFT, OwnerUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    You cannot assign an MFileStream to a MStream (although this is something we could think about doing). You should have access to an MStream (and the Read) method by calling the .BaseMembers property:

       var fs = new MFileStream();
       MStream ms = fs.BaseMembers;


    If the .BaseMembers property is not present, instantiate a MStream instance around the MFileSystem runtime instance:

       var fs = new MFileStream();
       var ms = new MStream(fs.Instance);

    Jonathan "Peli" de Halleux - Give us your input about Pex!

All Replies

  • Wednesday, October 28, 2009 2:48 PMPeliMSFT, OwnerUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    You cannot assign an MFileStream to a MStream (although this is something we could think about doing). You should have access to an MStream (and the Read) method by calling the .BaseMembers property:

       var fs = new MFileStream();
       MStream ms = fs.BaseMembers;


    If the .BaseMembers property is not present, instantiate a MStream instance around the MFileSystem runtime instance:

       var fs = new MFileStream();
       var ms = new MStream(fs.Instance);

    Jonathan "Peli" de Halleux - Give us your input about Pex!