How to Use AutoFixture with Immutable Entities in C# Unit Tests

AutoFixture is a popular .NET library used to generate test data for unit tests, but it behaves differently when working with immutable entities. While AutoFixture can successfully instantiate an immutable object using its factory method, it throws an unhandled exception when attempting to customize read-only properties via the Build().With() syntax. This issue surfaces when developers refactor their domain entities to be immutable — a recommended practice — and then find their existing AutoFixture-based tests breaking. The article, originally published on carlosvigueras.es, demonstrates the problem using an immutable User entity with a private constructor and a static Create method. A follow-up solution to resolve this incompatibility is promised in the same post.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in