xUnit将thirdParty类实例替换为伪实例



我的类的一部分将对象初始化为MLM(这需要大量的设置和安装(,我需要的是替换它用一个假的物体以一种简单的方式做同样的事情,

例如,如何使用伪对象测试以下代码

// LMXProxyServerClass is the library in which need a lot of installation 
private readonly LMXProxyServerClass lmxProxyServer; 

这是我在中使用的一个方法的例子

private bool CreateBindingWithoutPropagate(string attributeName, bool supervisory)
{
bool creatingBindingResult = false;
lock (mxAccessProxyLock)
{
if (!bindings.ContainsKey(attributeName))
{
try
{
logger.Debug("Adding item " + attributeName + " to bindings, not in list so add.");
// Add the handle to the mapping
lmxHandleToAttributeNameMapping.Add(attributeBinding.MxAttributeHandle, attributeName);
if (supervisory)
{
lmxProxyServer.DoSOmethingElse(yyyyyyyyyyyyyyyyyyyyyyy);
logger.Info(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx);
}
else
{
lmxProxyServer.DoSOmething(xxxxxxxx);
logger.Info(xxxxxxxxxxx);
}
// Add the binding to the list of bindings.
bindings.Add(attributeName, attributeBinding);
logger.Info("Creating binding for: " + attributeName);
creatingBindingResult = true;
}
catch (System.UnauthorizedAccessException unauthorizedAccessException)
{
logger.Error("xxxxxxxxxxx", attributeName);
throw ConvertExceptionToFault(unauthorizedAccessException);
}
catch (Exception ex)
{
throw ConvertExceptionToFault(ex);
}
}
}
return creatingBindingResult;
}

这个库是第三方的,所以我无法控制它,所以在测试中,我需要用假对象替换这个对象,这样我就不会在基本代码中做太多更改,并简化其他部件的测试

将代码与第三方实现问题紧密耦合会使代码难以单独进行单元测试。

相反,将第三方实现问题封装在一个抽象中,在测试时可以根据需要进行模拟。

例如,创建第三方依赖关系的抽象,只公开代码所需的内容。

public interface ILMXProxyServer {
void DoSOmethingElse(...);
void DoSOmething(...);
//...
}

并通过构造函数注入将其显式注入到依赖项中。

public class MyClass {
private readonly ILMXProxyServer lmxProxyServer; 
public MyClass(ILMXProxyServer lmxProxyServer) {
this.lmxProxyServer = lmxProxyServer;
}
//...other code omitted for brevity
}

方法保持不变,因为它们将调用抽象的公开成员。

运行时实现将包装/封装第三方依赖

public class MyLMXProxyServerWrapper : ILMXProxyServer {
// LMXProxyServerClass is the library in which need a lot of installation 
private readonly LMXProxyServerClass lmxProxyServer; 

public void DoSOmething(Something xxxxxxx){
lmxProxyServer.DoSOmething(xxxxxxxx);
}
//...code omitted for brevity
}

有了这种重构,代码现在更灵活了,可以在使用您选择的mocking框架进行隔离测试时,或者通过滚动您自己的特定于测试的实现来模拟/伪造代理服务器。

最新更新