简体   繁体   中英

How to print in NUnit with F#?

I try to print something with the NUnit test framework in F#. It is not working when I run the piece of code below. What is the problem?

I am using Visual Studio on an Mac if it matters.

module firsttry_test

open NUnit.Framework

[<SetUp>]
let Setup() = ()

[<Test>]
let Test1() = Assert.Pass()

let __a= printf ("Hello Test here!");;

You may need to put your code into a class type as shown in the official Microsoft docs here .

There are some issues with your code:

  • you can use SetUp only with class types
  • put your code in a module, or a class with a default constructor (if you want to use SetUp)
  • the let __a is global and not a function (there are no parens), so it only gets executed if something in the module gets accessed. Put it inside the test function and remove the let

It's fine to use module level let bindings for tests, only if you want to use SetUp you need to put it in a class.

The following is fine:

module MyTests =
    [<Test>]
    let Test1() = 
        printf ("Hello Test here!")
        Assert.Pass()

Note that it depends on the test runner where you will see the console output. For instance in VS a link is shown in the test output window, if you click it, you see the extra output. In NCrunch you'll see it directly in the result panel. Other runners may behave differently.

Some runners only show it when a test fails, in which case you'll have to access the raw output logs (Azure CI jobs that Microsoft uses behave like this).

Unfortunately, this does not work on Visual Studio for Mac. For getting output you need a failing test:

[<Test>]
let Test1() = 

   printfn "Hello Test here!"
   Assert.Fail()

Now you'll see the message in the Test Results Output Window. Sometimes is not enabled, but just click on it and you'll see it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM