This post explains how to configure AutoFixture.AutoFoq 3 so that
null values are never returned when using Foq 1.5.1 and newer.
Foq’s behavior for mock objects that have not been explicitly setup, is to return
null if the return type of a function is a reference type (e.g. a string):
AutoFixture is an opinionated library, and one of the opinions it holds is that nulls are invalid return values.
By the time AutoFixture.AutoFoq 3 was published Foq was still in version 1.0 with no specific hooks to override this behavior.
Foq now provides the necessary hooks to override this behavior and the rest of this post explains how to automate this when using AutoFixture.AutoFoq.
Ruben Bartelink originally discussed and proposed in Foq discussions about a
returnStrategy argument for members that have not been explicitly setup:
Configuring AutoFoq to use Foq’s returnStrategy argument
The existing AutoFoqCustomization has no specific hook to select Foq’s new
returnStrategy argument. This can be addressed when necessary with the customization shown below:
The only difference from the original AutoFoqCustomization is the usage of Foq’s
returnStrategy argument in the
The above test can be also written declaratively using AutoData theories: