【发布时间】:2018-04-17 16:04:48
【问题描述】:
除了少数方法外,NSubstitute 中是否有任何内置方法可以用其实例模拟一个类?
在示例中,我想保留实例的全部功能,但检查是否使用特定参数调用方法。
其实我就是这么做的
public class Wrapper: IInterface
{
public IInterface real;
public IInterface sub;
public void Wrapper(IIterface realInstance, IIterface nsubstitute)
{
real = realInstance;
sub = nsubstitute;
}
public void MethodThatShouldWorkAsAlways()
{
real.MethodThatShouldWorkAsAlways();
}
public intMethodToBeTested(int a)
{
return sub.MethodToBeTested();
}
}
这样做的原因是我正在测试足够复杂的东西,以至于我不能简单地手动创建包装器,这既费时又容易出错。如果 Nsubstitute 允许这样的东西会很好:
IIterface realMock = NSubstitute.Mock< IIterface>( new RealClass());
realMock.MethodThatShouldWorkAsAlways(); // regular logic
realMock.MethodToBeTested(4).Returns( 3); // overrides the method to always returns 3
但到目前为止我没有找到任何文档。
【问题讨论】:
-
模拟未密封的实际类。被覆盖的成员必须是虚拟的才能正常工作。
-
特别注意与使用部分模拟/订阅相关的警告。
-
测试实际实现有什么问题?
-
实现已测试,我需要测试使用它的类并验证最终调用了一个方法
标签: c# unit-testing mocking nsubstitute