Tricks
This page contains a list of tips and tricks to be used when dealing with special scenarios with AutoFixture
Random value from list of valid values
In case a certain type can assume a subset of the valid values, an instance of the ElementsBuilder<T>
class can be used to provide AutoFixture with the values to fish from.
It's important to note that a setup like the one above affects every instance of the customized type: this means that every instance of the customized type generated by this fixture will be picked from the specified values.
Random valid Encoding
By default, when requested an instance of type Encoding
, AutoFixture always returns Encoding.UTF8
.
It is possible to override the default setup by registering all supported encodings. To do so, we add an instance of ElementsBuilder<EncodingInfo>
to the set of customizations. We can then use Register
to instruct AutoFixture to extract an Encoding
from the random EncodingInfo
received.
Furthermore, we can use the above configuration to configure the string property of an object that could be parsed from a text file.
Here is the class used for this example
Working with streams
Classes exposing properties of type Stream
require special setup.
Here are some configurations that can be used when working with streams. The best setup might vary from case to case.
The following class will be used for the snippets below
NullStream
NullStream
The easiest scenario: every Stream
property receives the singleton value of the NullStream
class.
If a more targeted approach is needed, the construct With
can be used.
MemoryStream
MemoryStream
In case the system under test expects some data out of the stream, the MemoryStream
can be used to return the test data.
This setup will return a stream containing a certain amount of bytes. The amount is controlled by the Fixture.RepeatCount
property.
In the case the stream is expected to contain a random string, this setup can be used.
Finally, if the stream is expected to contain the serialized version of some data, this setup can be used (the example uses Newtonsoft.Json to serialize the payload)
These setups can also be applied on a specific property of a specific type using the construct With
.
Working with dictionaries
Normally dictionaries are created and filled with items whose key and value are randomly generated. Sometimes a dictionary with specific keys are needed.
Considering the class below,
The snippet below configures the type Options
so that its instances have the property Values
set to a dictionary containing an item with a well-known key and a value generated by AutoFixture.
Last updated