人们如何模拟 TcpClient(或 TcpClient 之类的东西)?
How do people approach mocking out TcpClient (or things like TcpClient)?
我有一个接收 TcpClient 的服务.我应该用其他更可笑的东西来包装它吗?我应该如何处理?
I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this?
当要模拟对测试不友好的类(即密封/未实现任何接口/方法不是虚拟的)时,您可能希望使用 <一个 href="http://en.wikipedia.org/wiki/Adapter_pattern" rel="noreferrer">Adapter 设计模式.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
ASP.NET Core 使用 Azure Active Directory 进行身份验证并ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 进行身
ASP.NET Core 2.0 Web API Azure Ad v2 令牌授权不起作用ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working(ASP.NET Core 2.0 Web API Azure Ad v2 令牌授权不起作用)
如何获取守护进程或服务器到 C# ASP.NET Web API 的How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API(如何获取守护进程或服务器到 C# ASP.N
异步调用时 Azure KeyVault Active Directory AcquireTokenAAzure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(异步调用时 Azure KeyVault Active Directory AcquireTokenAsync 超
使用电子邮件地址和应用程序密码从 oauth2/tokenGetting access token using email address and app password from oauth2/token(使用电子邮件地址和应用程序密码从 oauth2/token 获取访问令
新的 Azure AD 应用程序在通过管理门户更新之前无New Azure AD application doesn#39;t work until updated through management portal(新的 Azure AD 应用程序在通过管理门户更新之前无法运行