Mocking a record

34 views Asked by At

In my application, I have a bunch of DTOs, generally implemented as records. Various methods take these DTOs as parameters. The DTOs have quite a lot of properties, and when I'm unit testing the classes that use them, I don't always care about most of them. Quite often I want to be able to mock a DTO with only the properties that I care about set, in order to pass it to the system under test.

The trouble is, as an empty DTO isn't useful in actual operation, they don't have parameterless constructors, and thus Moq can't instantiate them. I really don't want to have to set a couple of dozen random properties for each unit test, which I'd have to if I created real DTOs instead of mocking them, so what's the best approach here?

1

There are 1 answers

0
Mark Seemann On

As the comment says, one option is to use AutoFixture, which (full disclosure) I originally wrote, but I'm no longer involved with.

There are other libraries similar to AutoFixture that do something similar.

If you don't want something quite as randomized, you may instead want to use Test Data Builders. They require more manual code, but may be easier to grasp if you're working in a code base with developers of diverse experience and skill level.

The reason I moved on from AutoFixture is that I now address such concerns with property-based testing instead. The most mature property-based testing library on .NET is FsCheck, but if you want something that's native to C#, you can also try CsCheck. Finally, Hedgehog is also good.