【问题标题】:How to mock with NSubstitute in IntegrationTest如何在 IntegrationTest 中使用 NSubstitute 进行模拟
【发布时间】:2020-09-27 08:32:14
【问题描述】:

我在集成测试中使用了一个 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 表达式转换为类型“对象”,因为它不是委托类型。

我们应该如何使用 Substitute 来代替上面的例子?

【问题讨论】:

  • 我没有投反对票,但问题标题有点含糊。也许可以改进。

标签: c# xunit nsubstitute


【解决方案1】:

.For 的参数在 NSubstitute 中作为构造函数参数传递。这对于用虚拟成员替换类可能很有用。

另见the code of Substitute

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多