Question

I'm writing unit tests for my F# library using F#, Visual Studio Unit Testing Framework (aka MSTest) and FluentAssertions.

Test method should have return type either void or Task. In C# that's easy:

[TestMethod]
public void TestMethod1()
{
    false.Should().BeFalse();
}

In F# I have the following:

[<TestMethod>]
member this.TestMethod1() =
    false.Should().BeFalse(null)
    |> ignore

Otherwise return type is changed to FluentAssertions.PrimitivesBooleanAssertions so Test Runner doesn't see it.

How to avoid having |> ignore in the end of each test?

Was it helpful?

Solution

|> ignore is required here, since the signature of TestMethod1 is inferred from "the inside out". Consider that in C#, the return type of a method is required in the method declaration. These are deep differences between the languages.

"Fluent" APIs are a nuisance in F#, since they involve instance methods that both have an effect and return a value, a red-flag in F#. That is, while side-effects are permitted in F#, they are somewhat quarantined, both in the language specification and by convention. It is expected that a method returning unit has an effect, but conversely a method returning a non-unit value is expected to be pure.

Moreover, fluent APIs seek to solve limitations in languages such as C# that F# doesn't have or solves differently. For example, in F#, the pipe operator + immutable data structure transformations is comparable to a fluent API in an imperative language.

Try using a more idiomatic F# unit testing assertion library, such as Unquote (disclaimer, I am the author). It exploits many of the strengths of F# in the same way FluentAssertions tries to make up for the weaknesses of C#.

OTHER TIPS

Just add () at the end of your function

This will return unit

In F#, you could try instead FsUnit

You cannot return void in F#, thanks Gods! When you use |> ignore at the end of a method, the method returns unit. In F#,

'System.Void' can only be used as 'typeof<System.Void>'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top