7

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?

Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154
Martin
  • 23,844
  • 55
  • 201
  • 327

2 Answers2

11

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>();
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
6

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.

Nikos Baxevanis
  • 10,868
  • 2
  • 46
  • 80
  • But this I believe is for Moq, I am using NSubstitute, and the Mock - Mock isn't found or exists.. – Martin Jun 26 '13 at 08:01