Using collections with MemberData attribute in F#
Working with collections of custom types in xUnit always felt clumsy. To pass such a set of data, you had either create a property or a whole class. No matter which options you choose, it's a lot of boilerplate.
What a pleasant surprise was how less cumbersome it is to do in F#.
The plan is to compare two value objects defined as a type alias:
type StationName = StationName of string
The test doesn't require much code as well.
[<Theory>]
[<MemberData(nameof (stationsData))>]
let ``compare stations correctly`` (station, otherStation, expected) =
let result = station = otherStation
Assert.Equal(expected, result)
C# developers, watch out for =
comparison!
And now the clou.
Take a look at stationsData
definition:
let stationsData: seq<array<Object>> =
seq {
yield
[| "Sopot" |> StationName
"Sopot" |> StationName
true
|]
yield
[| "Sopot" |> StationName
"Gdynia" |> StationName
false |]
}
Instead of the type definition for stationsData
you could omit it and box every value using |> box
. I found the former approach more readable.
Anyway, that's all the code you need. Simple, isn't it?