TDD和​​惩戒出来的TcpClient [英] TDD and Mocking out TcpClient

查看:143
本文介绍了TDD和​​惩戒出来的TcpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何进场的人嘲讽了TcpClient的(或类似的东西TcpClient的)?

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

我有一个发生在一个TcpClient的服务。我应该换在其他更多的东西mockable?我应该如何处理呢?

I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this?

推荐答案

在来模拟类未测试友好(即密封/不实施任何接口/方法不是虚拟的),你可能会想使用适配器的设计模式。

When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the Adapter design pattern.

在这个模式中添加实现接口的包装类。然后,您应该嘲笑接口,并确保所有代码使用这个接口,而不是不友好的具体类。它看起来是这样的:

In this pattern you add a wrapping class that implements an interface. You should then mock the interface, and make sure all your code uses that interface instead of the unfriendly concrete class. It would look something like this:

public interface ITcpClient
{
   Stream GetStream(); 
   // Anything you need here       
}
public class TcpClientAdapter: ITcpClient
{
   private TcpClient wrappedClient;
   public TcpClientAdapter(TcpClient client)
   {
    wrappedClient = client;
   }

   public Stream GetStream()
   {
     return wrappedClient.GetStream();
   }
}

这篇关于TDD和​​惩戒出来的TcpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆