[英]How can you mock the methods from a class if you have no control over the class?
I'm using Xunit and Moq for unit testing.我正在使用 Xunit 和 Moq 进行单元测试。 So far I was able to succesfully mock and test methods from interfaces.
到目前为止,我能够成功地从接口模拟和测试方法。 But how am I supposed to mock and test the methods of a class that I have no control over.
但是我应该如何模拟和测试我无法控制的 class 的方法。 The class has no interface and the methods are not virtual.
class 没有接口,方法也不是虚拟的。
I looked into Type Mock Isolator, but I could not make that work, and also that is not a feasible solution because it's paid and only has a 14 day trial, and I need to do this long term.我研究了 Type Mock Isolator,但我无法做到这一点,而且这不是一个可行的解决方案,因为它是付费的,只有 14 天的试用期,我需要长期这样做。
What are my options?我有哪些选择?
Create a wrapper for the dependency.为依赖项创建一个包装器。 You don't need to test the implementation of code you didn't write.
您无需测试您未编写的代码的实现。 Mock the dependency wrapper with the anticipated or hypothetical outputs.
用预期或假设的输出模拟依赖包装器。
public sealed class SomeBadDependency
{
public int CalculateSuperSecretValue(int inputX, int inputY)
{
return Math.Max(inputX, inputY);
}
}
public interface IDependencyWrapper
{
int CalculateSuperSecretValue(int inputX, int inputY);
}
public sealed class DependencyWrapper : IDependencyWrapper
{
private readonly SomeBadDependency _someBadDependency;
public DependencyWrapper(SomeBadDependency someBadDependency)
{
_someBadDependency = someBadDependency;
}
public int CalculateSuperSecretValue(int inputX, int inputY)
{
return _someBadDependency.CalculateSuperSecretValue(inputX, inputY);
}
}
public sealed class YourCode
{
private readonly IDependencyWrapper _dependencyWrapper;
public YourCode(IDependencyWrapper dependencyWrapper)
{
_dependencyWrapper = dependencyWrapper;
}
public decimal CalculateYourValue(decimal inputX, decimal inputY)
{
return _dependencyWrapper.CalculateSuperSecretValue((int) inputX, (int) inputY);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.