6

Using collections with MemberData attribute in F#

 3 years ago
source link: https://blog.ciechowski.net/using-collections-with-memberdata-attribute-in-f
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK