Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Freeze a null instance in AutoFixture

Tags:

autofixture

I'm using Autofixture as a SUT factory and am having difficulty Freezing null instances.

I'd like to do something like:

_fixture.Freeze<IPayPalConfiguration>(c => null);

but quickly realized that was wrong. I've worked around the problem using this:

_fixture.Inject((IMyInterface)null);

but it doesn't seem right.

Hopefully someone will contribute the correct solution to the HiveMind.

like image 870
Peter McEvoy Avatar asked Aug 31 '12 15:08

Peter McEvoy


1 Answers

Internally, Freeze creates an instance of the requested type (e.g. IPayPalConfiguration) and then injects it so it will always return that instance when you request it again.

In that particular case, by doing _fixture.Inject((IPayPalConfiguration)null) you inject the null reference manually so you skip the creation part of the Freeze method. You freeze the IPayPalConfiguration to a single value (actually, a null reference here) but in a manual way.

Keep in mind that this _fixture.Freeze<IPayPalConfiguration>(c => null) passes a null reference for the method that will try to resolve the IPayPalConfiguration and for that reason an ArgumentNullException is thrown.

like image 104
Nikos Baxevanis Avatar answered Sep 22 '22 14:09

Nikos Baxevanis