Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofixture + NSubstitute: Freezing a mock?

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?

like image 228
Martin Avatar asked Jun 25 '13 15:06

Martin


2 Answers

Based on inferences from this Mocking tools comparison article by Richard Banks, and how AutoMoq works, I believe:

  • NSubstitute doesn't have a separation between the Mock and the Mock.Object like Moq does
  • A AutoFixture.Auto* extensions hook in a SpecimenBuilderNode to supply the [mocked] implementation of interfaces, i.e. fixture.Create<IFileUtils>() should work
  • Freeze is equivalent to a var result = fixture.Create<IFileUtils>(); fixture.Inject(result)

Therefore you should just be able to say:

var fileUtilMock = fixture.Freeze<IFileUtils>();
like image 64
Ruben Bartelink Avatar answered Oct 21 '22 04:10

Ruben Bartelink


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.

like image 26
Nikos Baxevanis Avatar answered Oct 21 '22 04:10

Nikos Baxevanis