I am trying to get access to a mocked (via Nsubstitute) class that was injected onto the constructor.
I was using the following code
var fixture = new Fixture()
.Customize(new AutoNSubstituteCustomization());
var sut = fixture.Create<MyService>();
The sut is created sucessfully, and a mocked version of an interface called "IFileUtils" is injected on the constructor of "MyService".
but i need access to it, so after reading I believe I need to freeze the object so I have access to it like so
var fileUtilMock= fixture.Freeze<Mock<IFileUtils>>();
But this code I believe is a Moq syntax as "Mock" can't be found.
Normally to create a Nsubstitute of a class you do the following
var fileUtilMock= Substitute.For<IFileUtils>();
but of course this isn't frozen so its not used and injected into the constructor.
can anyone help?
Based on inferences from this Mocking tools comparison article by Richard Banks, and how AutoMoq works, I believe:
Mock
and the Mock.Object
like Moq doesSpecimenBuilderNode
to supply the [mocked] implementation of interfaces, i.e. fixture.Create<IFileUtils>()
should workvar result = fixture.Create<IFileUtils>(); fixture.Inject(result)
Therefore you should just be able to say:
var fileUtilMock = fixture.Freeze<IFileUtils>();
You have to Freeze the auto-mocked instance before creating the MyService
instance.
Update:
As Ruben Bartelink points out, with NSubstitute all you have to do is:
var fixture = new Fixture()
.Customize(new AutoNSubstituteCustomization());
var substitute = fixture.Freeze<IFileUtils>();
..and then use NSubstitute's extension methods.
That way the same, frozen, instance will be supplied to MyService
constructor.
Example:
For an interface IInterface
:
public interface IInterface
{
object MakeIt(object obj);
}
All you have to do with is:
var substitute = fixture.Freeze<IInterface>();
substitute.MakeIt(dummy).Returns(null);
Returns
is actually an extension method in NSubstitute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With