Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFixture and fluent Moq syntax

I've been using Moq for a while, and for brevity I more often than not express setups using the fluent syntax of Mock.Of...

var foo = Mock.Of<IFoo>(f => f.Method(It.IsAny<string>()) == 7 && f.Property == "Hi");
var sut = new Whatever(foo);

Recently, I've started playing around with AutoFixture and can't seem to find any equivalent syntax for expressing multiple setups at once. I understand that I can express the same thing using Freeze...

var foo = fixture.Freeze<Mock<IFoo>>();
foo.Setup(f => f.Method(It.IsAny<string>()).Returns(7);
foo.Setup(f => f.Property).Returns("Hi");
var sut = fixture.Create<Whatever>();

...but if at all possible, I'd like to get the benefits of automocking, and keep the brevity of the fluent Moq setups. Stylistic arguments aside, does AutoFixture expose any way for me to express those setups fluently? If not, is there any optimization I can use to make the AutoFixture setups more terse?

like image 432
ScheuNZ Avatar asked Apr 23 '15 00:04

ScheuNZ


1 Answers

You could create the mock yourself using Moq's fluent API, and then inject it back into the fixture:

var foo = Mock.Of<IFoo>(f => f.Method(It.IsAny<string>()) == 7 && f.Property == "Hi");
fixture.Inject(foo);

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

If you're using the AutoMoqCustomization, then the code above will do the same thing as the code you posted, apart from not setting CallBase = true and DefaultValue = DefaultValue.Mock;.

If you're using AutoConfiguredMoqCustomization, then this code will not setup any additional members, whereas the customization would. If you want to reap the benefits of AutoConfiguredMoqCustomization and use Moq's fluent API, I'm afraid that's not possible.

like image 58
dcastro Avatar answered Sep 18 '22 14:09

dcastro