TDD and Mocking out TcpClient

前端 未结 3 2059
清歌不尽
清歌不尽 2020-12-14 12:14

How do people approach mocking out TcpClient (or things like TcpClient)?

I have a service that takes in a TcpClient. Should I wrap that in something else more mocka

3条回答
  •  时光说笑
    2020-12-14 12:38

    I think @Hitchhiker is on the right track, but I also like to think about abstracting out things like that just a step further.

    I wouldn't mock out the TcpClient directly, because that would still tie you too closely to the underlying implementation even though you've written tests. That is, your implementation is tied to a TcpClient method specifically. Personally, I would try something like this:

       [Test]
        public void TestInput(){
    
           NetworkInputSource mockInput = mocks.CreateMock();
           Consumer c = new Consumer(mockInput);
    
           c.ReadAll();
        //   c.Read();
        //   c.ReadLine();
    
        }
    
        public class TcpClientAdapter : NetworkInputSource
        {
           private TcpClient _client;
           public string ReadAll()
           { 
               return new StreamReader(_tcpClient.GetStream()).ReadToEnd();
           }
    
           public string Read() { ... }
           public string ReadLine() { ... }
        }
    
        public interface NetworkInputSource
        {
           public string ReadAll(); 
           public string Read();
           public string ReadLine();
        }
    

    This implementation will decouple you from Tcp related details altogether (if that is a design goal), and you can even pipe in test input from a hard coded set of values, or a test input file. Very hand if you are on the road to testing your code for the long haul.

提交回复
热议问题