AutoFixture.Idioms allows us to write unit tests which tend to follow common templates. Mark Seemann calls it Idiomatic unit testing. Previously we have discussed about testing guard clauses using Guard Assertions. In this post we are going to discuss about testing writable properties. Unit testing property assignments is a big part of our unit tests. AutoFixture.Idioms provides WritablePropertyAssertion to test all such properties in a single unit tests. This minimizes the unit testing effort and keeps the unit tests less brittle.
You would need to add the nuget packages for xUnit , AutoFixture and AutoFixture.Idioms as described in the previous post. Let's add a Student class in our project. It has two writable properties StudentId and StudentName.
You might be thinking about separate tests for each writable property in Student. This makes it more difficult as the number of such properties increase. With AutoFixture, we just need one unit test to verify that the properties are being correctly assigned and they reflect the assigned value afterwards. Just see how simple the unit test has become.
Let's assume we have a defect in our code which is causing a property not to be assigned properly. Here we have StudentId always return a fixed value no matter the value assigned to it. This is definitely a defect. Let's update the code as follows:
The unit test should check for such defects and should report. When we run the unit test now, it does fail with the following details: