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?
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.
Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.
|> 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#.
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>'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With