I want to unit test a weather parsing method. My first approach was to let autofixture create a weather object and than create the query response from it. But the weather class contains multiple limitations:
- Humidity is a percentage value and must be between 1-100
- Temperatures must be above the minimum depending on the temperature unit
Is it possible to solve this problems and is it worth to use this approach or just hard code a query response and the expected weather object?
As outlined elsewhere, I'd recommend a solution where you let test-driven development provide feedback on your design. Instead of treating humidity and temperature as primitives, refactor to a good domain model. As an example, create a new value object for both:
The type
Celcius
looks similar:This guarantees that if you have a
Humidity
orCelcius
object, they're valid, because they protect their invariants. This is valuable in your production code, but also provides testing benefits.Weather
simply looks like this, now:You can override
Equals
andGetHashCode
forWeather
as well, if you like, but it's not important for this example.For AutoFixture, you can now define customizations for both types:
and
You can collect those (and others) in a
CompositeCustomization
:Now you can write tests as simple as this:
This test passes.
Granted, this looks like a lot of work for a single test, but the point is that if you collect all domain-specific customizations in
MyConventions
, you can reuse that single convention across hundreds of tests, because it guarantess that all domain objects are valid.Not only does it make your test code more maintainable, it also makes you production code more maintainable.