问题描述
我有一个我在集成测试中使用的ContainerFixture类,如下所示:
services.AddSingleton(Mock.Of<IWebHostEnvironment>(w =>
w.EnvironmentName == "Development" &&
w.ApplicationName == "Application.WebUI"));
在上面的示例中,我使用的是Moq,但我想使用NSubstitute。
当我用Substitute.For替换Mock.of时,出现以下错误:
services.AddSingleton(Substitute.For<IWebHostEnvironment>(w =>
w.EnvironmentName == "Development" &&
w.ApplicationName == "Application.WebUI"));
错误:由于lambda表达式不是委托类型,因此无法将其转换为“对象”类型。
在上面的示例中,我们应该如何使用“替换”?
解决方法
.For
的参数在NSubstitute中作为构造函数参数传递。这对于用虚拟成员替换类可能很有用。
public static T For<T>(params object[] constructorArguments)
您的示例中的NSubstitute中的等效项:
var env = Substitute.For<IWebHostEnvironment>();
env.EnvironmentName.Returns("Development");
env.ApplicationName.Returns("Application.WebUI");
services.AddSingleton(env);