Autofixture + NSubstitute:冻结模拟?

Mar*_*tin 6 c# mocking autofixture nsubstitute

我试图访问注入构造函数的模拟(通过Nsubstitute)类.

我使用以下代码

var fixture = new Fixture()
    .Customize(new AutoNSubstituteCustomization());

var sut = fixture.Create<MyService>();
Run Code Online (Sandbox Code Playgroud)

sut是成功创建的,并且在"MyService"的构造函数上注入了一个名为"IFileUtils"的接口的模拟版本.

但我需要访问它,所以阅读后我相信我需要冻结对象,所以我可以这样访问它

var fileUtilMock= fixture.Freeze<Mock<IFileUtils>>();
Run Code Online (Sandbox Code Playgroud)

但是我认为这段代码是Moq语法,因为"Mock"无法找到.

通常要创建一个类的Nsubstitute,您可以执行以下操作

var fileUtilMock= Substitute.For<IFileUtils>();
Run Code Online (Sandbox Code Playgroud)

但当然这并没有冻结,所以它没有被使用并注入构造函数中.

有人可以帮忙吗?

Rub*_*ink 10

基于理查德班克斯的Mocking工具比较文章以及AutoMoq如何工作的推论,我相信:

  • NSubstitute没有之间的分离MockMock.Object喜欢起订量不
  • 一个AutoFixture.Auto*扩展钩子,SpecimenBuilderNode用于提供接口的[ 模拟]实现,即fixture.Create<IFileUtils>()应该工作
  • 冻结相当于一个 var result = fixture.Create<IFileUtils>(); fixture.Inject(result)

所以你应该只能说:

var fileUtilMock = fixture.Freeze<IFileUtils>();
Run Code Online (Sandbox Code Playgroud)


Nik*_*nis 6

您必须在创建实例之前冻结自动模拟的MyService实例.

更新:

正如Ruben Bartelink指出的那样,在NSubstitute所有你需要做的就是:

var fixture = new Fixture()
    .Customize(new AutoNSubstituteCustomization());

var substitute = fixture.Freeze<IFileUtils>();
Run Code Online (Sandbox Code Playgroud)

..然后使用NSubstitute的扩展方法.

这样,冻结的实例将被提供给MyService构造函数.

示例:

对于接口IInterface:

public interface IInterface
{
    object MakeIt(object obj);
}
Run Code Online (Sandbox Code Playgroud)

你所要做的就是:

 var substitute = fixture.Freeze<IInterface>();
 substitute.MakeIt(dummy).Returns(null);
Run Code Online (Sandbox Code Playgroud)

Returns 实际上是NSubstitute中的扩展方法.