2013-06-25 49 views
5

我想获得一个被注入到构造函数中的模拟(通过Nsubstitute)类。Autofixture + NSubstitute:冻结模拟?

我用下面的代码

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

var sut = fixture.Create<MyService>(); 

是成功创建的SUT和接口的嘲笑版本,称为“IFileUtils”注入的“则将MyService”的构造。

,但我需要访问它,所以读我相信以后我需要冻结的对象,所以我有机会获得它像这样

var fileUtilMock= fixture.Freeze<Mock<IFileUtils>>(); 

但这种代码,我相信这是一个起订量语法为“模拟”无法找到。

通常建立你做一个类的Nsubstitute以下

var fileUtilMock= Substitute.For<IFileUtils>(); 

,但当然这不是冻结所以它不是用来和注入的构造。

任何人都可以帮忙吗?

回答

10

this Mocking tools comparison article by Richard Banks和AutoMoq是如何工作的,我相信:

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

因此,你应该只能够说:

var fileUtilMock = fixture.Freeze<IFileUtils>(); 
+0

@daniel hilgarth是我推论的任何好东西:D随意编辑尽可能多的,你喜欢和/或告诉我删除帖子! –

6

你必须冻结创建MyService实例之前的自动模拟实例。

更新

由于鲁本Bartelink指出,随着NSubstitute所有你需要做的是:

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

var substitute = fixture.Freeze<IFileUtils>(); 

..和再使用NSubstitute的扩展方法。

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

对于接口IInterface

public interface IInterface 
{ 
    object MakeIt(object obj); 
} 

所有您有做的是:

var substitute = fixture.Freeze<IInterface>(); 
substitute.MakeIt(dummy).Returns(null); 

Returns实际上是NSubstitute扩展方法。基于推论

+0

但是这个我相信是起订量,我使用NSubstitute,以及素 - 找不到或存在模拟.. – Martin

+0

你是对的。我刚刚更新了答案。 –

相关问题