Search code examples
c#unit-testingarchitecture

How can I develop a testable TcpClient / TcpListener Wrapper


i want to develop a testable TcpClient / TcpListener wrapper. I want to be able to mock the incoming and outgoing data.

I want to do this because i have higher tier components that should react on network messages. For testing reasons i want to mock (the network) them.

Can some one please give me a kick in the right direction?


Solution

  • You could use the Decorator Pattern

    • Make your very own class that just wraps the TcpClient
    • This class simply does pass through calls to functions in TcpClient.
    • An overloaded constructor to this class could accept an instance of an actual tcp client which it would wrap, if creating one is involved.
    • Extract the interface so your new class should implement the interface ITcpClient
    • Update all your dependencies to use the new interface ITcpClient
    • Your new interface is now mockable, inject your mocks were appropriate and test away :)

    Repeat the same for TcpServer.