Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep method return type 'void' in F#?

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?

like image 786
abatishchev Avatar asked Mar 12 '14 23:03

abatishchev


People also ask

Can I use return for a method of the return type void?

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.

What is the return type of void function?

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.


3 Answers

|> 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#.

like image 107
Stephen Swensen Avatar answered Oct 04 '22 18:10

Stephen Swensen


Just add () at the end of your function

This will return unit

like image 45
John Palmer Avatar answered Oct 04 '22 17:10

John Palmer


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>'

like image 32
V.B. Avatar answered Oct 04 '22 18:10

V.B.