AutoFixture作为Automocking容器与Automocking差异?

我开始使用moq但是根据我的理解,我总是要模拟所有可以调用的方法,即使我真的不关心它们。

有时需要很长时间来模拟你忘记你想做什么的东西。 所以我一直在看自动模拟,但我不确定我应该使用什么。

AutoFixture作为自动模拟容器

Automocking

我根本不知道如何使用第一个。 我有点得到第二个但从未真正尝试过。

我不确定一个人是否比另一个好。 我唯一知道的是我使用AutoFixtures已经是第一个的依赖。

所以也许从长远来看,与第一个一起使用是有意义的,但就像我说我找不到任何关于如何使用它的基本教程。

编辑

我试图遵循“Nikos Baxevanis”的例子,但我遇到了错误。

Failure: System.ArgumentException : A matching constructor for the given arguments was not found on the mocked type. ----> System.MissingMethodException : Constructor on type 'DatabaseProxyded46c36c8524889972231ef23659a72' not found. var fixture = new Fixture().Customize(new AutoMoqCustomization()); var fooMock = fixture.Freeze<Mock>(); // fooMock.Setup(x => x.GetAccounts(It.IsAny())); var sut = fixture.CreateAnonymous(); sut.Apply(); fooMock.VerifyAll(); 

我认为这是因为我的petapoco unitOfWork财产

 PetaPoco.Database Db { get; } 

不确定我是否要以某种方式嘲笑这个或什么。

虽然我从未使用过moq-contrib Automocking ,但我可能会提供一些使用AutoFixture作为自动模拟容器的信息。

目前支持Moq,Rhino Mocks,FakeItEasy和NSubstitute。 只需安装相应的扩展名AutoMoq , AutoRhinoMocks , AutoFakeItEasy和AutoNSubstitute即可 。

一旦您安装了Auto Mocking的其中一个扩展, 额外的呼叫就是:

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

(或者如果你使用的是Rhino Mocks)

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

(或者如果你使用的是FakeItEasy)

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

(或者如果你使用的是NSubstitute)

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

例1

 public class MyController : IController { public MyController(IFoo foo) { } } public interface IFoo { } 

以下是如何使用AutoFixture创建MyController类的实例:

 var fixture = new Fixture() .Customize(new AutoMoqCustomization()); var sut = fixture.CreateAnonymous(); 

现在,如果你检查sut变量,你会看到IFoo是一个模拟实例(类型名称类似于Castle.Proxies.IFooProxy)

例2

这个例子扩展了前一个例子。

您可以指示AutoFixture使用您自己的,预先配置的模拟实例:

 var fooMock = fixture.Freeze>(); // At this point you may setup expectation(s) on the fooMock. var sut = fixture.CreateAnonymous(); // This instance now uses the already created fooMock. // Verify any expectation(s). 

这基本上就是它 – 但它可以更进一步!

下面是使用AutoFixture与xUnit.net 扩展名相关的前面示例。

例1

 [Theory, AutoMoqData] public void TestMethod(MyController sut) { // Start using the sut instance directly. } 

例2

 [Theory, AutoMoqData] public void TestMethod([Frozen]Mock fooMock, MyController sut) { // At this point you may setup expectation(s) on the fooMock. // The sut instance now uses the already created fooMock. // Verify any expectation(s). } 

您可以在此博客文章中找到更多信息,其中包含与AutoFixture,xUnit.net和Auto Mocking相关的所有相关内容的链接。

希望有所帮助。