How to save the return method of the 'void' method in F #?

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

The testing method must have a return type of either void or Task. In C #, this is easy:

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

In F #, I have the following:

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

Otherwise, the return type changes to FluentAssertions.PrimitivesBooleanAssertions , so Test Runner does not see it.

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

+6
source share
3 answers

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

"Free" APIs are a nuisance in F #, because they include instance methods that have an effect and return a value, the red flag in F #. That is, although side effects are allowed in F #, they are quarantined somewhat, both in the language specification and by convention. It is expected that the method returning unit has an effect, but, on the contrary, it is expected that the method returning non-unit value will be clean.

In addition, fluent APIs seek to solve restrictions in languages ​​such as C #, which F # does not have or decides otherwise. For example, in F #, the pipe operator + immutable data structure transformations is comparable to a white API in an imperative language.

Try using a more idiomatic F # module test approval library such as Unquote (disclaimer, I'm the author). It uses many of F #'s strengths in the same way FluentAssertions tries to make up for C #'s flaws.

+12
source

Just add () to the end of your function

This will result in a unit return.

+4
source

In F # you can try instead of FsUnit

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

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

+1
source

All Articles