How to moq a NetworkStream in a unit test?

后端 未结 3 561
滥情空心
滥情空心 2020-12-15 20:53

I\'m using Moq & NUnit as a unit test framework.

I\'ve written a method that is given a NetworkStream object as a parameter:

public static void R         


        
相关标签:
3条回答
  • 2020-12-15 21:16

    Put the NetworkStream behind a simple interface (with only the calls you need) and mock that.

    0 讨论(0)
  • 2020-12-15 21:30

    You cannot mock the NetworkStream with moq since it is not an abstract class or an interface. You can however create an abstraction on top of it and change your method to accept an instance of that abstraction. It could be something like this:

    public interface IMyNetworkStream
    {
        int Read([In, Out] byte[] buffer, int offset, int size);
        bool DataAvailable {get;}
    }
    

    Now you create a class that implements the interface:

    public class MyNetworkStream : IMyNetworkStream
    {
         private NetworkStream stream;
    
         public MyNetworkStream(NetworkStream ns)
         {
             if(ns == null) throw new ArgumentNullException("ns");
             this.stream = ns;
         }
    
         public bool DataAvailable
         {
             get
             {
                 return this.stream.DataAvailable;
             }
         }
    
         public int Read([In, Out] byte[] buffer, int offset, int size)
         {
             return this.stream.Read(buffer, offset, size);
         }
    
    }
    

    Now you can change your method signature to use an instance of IMyNetworkStream and use Moq to create a mock of IMyNetworkStream.

    0 讨论(0)
  • 2020-12-15 21:38

    As suggested in the comments - is it possible for you to change the type to Stream, so that you, during testing, can pass a MemoryStream instead?

    0 讨论(0)
提交回复
热议问题