Should property tests run with unit tests when using the RGR methodology? - unit-testing

Should property tests run with unit tests when using the RGR methodology?
RGR: Red -> Green -> Refactor
I noticed that a unit test that I have executes in 18ms.
However, my property test for the same method takes 215ms.
module Tests.Units
open FsUnit
open NUnit.Framework
open NUnit.Core.Extensibility
open FsCheck.NUnit
open FsCheck.NUnit.Addin
open FsCheck
let add x y = (x + y)
let commutativeProperty x y =
let result1 = add x y
let result2 = add y x // reversed params
result1 = result2
[<Test>]
let ``When I add two numbers, the result should not depend on parameter order``()=
Check.Quick commutativeProperty
[<Test>]
let ``add two numbers`` () =
add 2 3 |> should equal (5)
So my property test takes a quarter of a second to execute.
In addition, this is just one simple property test.
What is an effective method for running property tests?
Just check-ins?

With default settings, each FsCheck property runs 100 times, so it's not surprising that it's slower. Notice, though, that it isn't 100 times slower.
I often use the Red/Green/Refactor process when writing property tests (for the targeted function), and find that it works well.
It's slower than when doing TDD in C# (also because the F# compiler is slower than the C# compiler). On the other hand, the F# type system is much more expressive, so I also find that I rely more on the type system than I would in C#. This means that I need to write fewer tests.
All in all, I find that the combination of F# and FsCheck a net win over C# and plain unit testing.

Related

Unit testing side effects in Elixir

I'm writing a unit test for a function that calls out to module as part of a side effect of invoking it:
defmodule HeimdallrWeb.VerifyController do
use HeimdallrWeb, :controller
def verify(conn, _params) do
[forwarded_host | _tail] = get_req_header(conn, "x-forwarded-host")
case is_preview_page?(forwarded_host) do
{:ok, false} ->
conn |> send_resp(200, "")
{:ok, %Heimdallr.Commits.Commit{} = commit} ->
Heimdallr.Commits.touch_commit(commit)
conn |> send_resp(200, "")
{:not_found, _reason} ->
conn |> send_resp(200, "")
end
end
end
The side effect is triggered from the line Heimdallr.Commits.touch_commit(commit).
A few questions about this:
Should my unit test be concerned with testing the effects of the touch_commit method.
If so, should I think about passing in a generic "touch" function to verify method to make it easier to test. This might be difficult due to the nature of Phoenix / Elixirs routing system, I haven't investigated.
If I was using Rails / Ruby / Rspec then I'd set an expectation that a class level method would be called on the HeimdallrCommits module.
My concern and reason for writing the test is that in the future I may accidentally remove the functionality that is touching a commit by deleting or commenting out the line etc.
I would say 1: No. And that is to keep the complexity low in your test. You only want to test (whatever it is you want to test) in a method, the rest should be mocked ignored. What you could do is verify what your method have invoked touch_commit - should be part of a good mocking framework. Those are my 5 cent, sorry to say that I am not familiar with phoenix/elixir so I can't give you any working examples. Like the verify method i Mockito or Moq is what I am thinking of..

Unit tests with different severity

I'm testing a set of classes and my unit tests so far are along the lines
1. read in some data from file X
2. create new object Y
3. sanity assert some basic properties of Y
4. assert advanced properties of Y
There's about 30 of these tests, that differ in input/properties of Y that can be checked. However, at the current project state, it sometimes crashes at #2 or already fails at #3. It should never crash at #1. For the time being, I'm accepting all failures at #4.
I'd like to e.g. see a list of unit tests that fail at #3, but so far ignore all those that fail at #4. What's the standard approach/terminology to create this? I'm using JUnit for Java with Eclipse.
You need reporting/filtering on your unit test results.
jUnit itself wants your tests to pass, fail, or not run - nothing in between.
However, it doesn't care much about how those results are tied to passing/failing the build, or reported.
Using tools like maven (surefire execution plugin) and some custom code, you can categorize your tests to distinguish between 'hard failures', 'bad, but let's go on', etc. But that's build validation or reporting based on test results rather than testing.
(Currently, our build process relies on annotations such as #Category(WorkInProgress.class) for each test method to decide what's critical and what's not).
What I could think of would be to create assert methods that check some system property as to whether to execute the assert:
public static void assertTrue(boolean assertion, int assertionLevel){
int pro = getSystemProperty(...);
if (pro >= assertionLevel){
Assert.assertTrue(assertion);
}
}

Selective running of tests in HUnit

Test.HUnit provides a big red button to run a test:
runTestTT :: Test -> IO Counts
As there is a need to structure large test suites, Test is not a single test but is actually a labelled rose tree with Assertion in leaves:
data Test
= TestCase Assertion | TestList [Test] | TestLabel String Test
-- Defined in `Test.HUnit.Base'
It's not abstract so it's possible to process it. One particularly useful processing is extraction of subtrees by paths:
byPath = flip $ foldl f where
f (TestList l) = (l !!)
f (TestLabel _ t) = const t
f t = const t
So for example I can run a single subsuite runTestTT $ byPath [1] tests or a particular test runTestTT $ byPath [1,7,3] tests identified by test path instead of waiting for whole suite.
One disadvantage of the homegrown tool is that test paths are not preserved (shortened).
Is there such processing helper tool already on Hackage?
The closest to your needs seem to be the libraries and programs that abstract over HUnit, Quickcheck and other tests, and have their own test name grouping and management infrastructure, e.g. test-framework. It provides you with a main function that takes command line arguments, including one that allows you to specify a test or test group to run (by globbing on the name).

What unit testing frameworks are available for F#

I am looking specifically for frameworks that allow me to take advantage of unique features of the language. I am aware of FsUnit. Would you recommend something else, and why?
My own unit testing library, Unquote, takes advantage of F# quotations to allow you to write test assertions as plain, statically checked F# boolean expressions and automatically produces nice step-by-step test failure messages. For example, the following failing xUnit test
[<Fact>]
let ``demo Unquote xUnit support`` () =
test <# ([3; 2; 1; 0] |> List.map ((+) 1)) = [1 + 3..1 + 0] #>
produces the following failure message
Test 'Module.demo Unquote xUnit support' failed:
([3; 2; 1; 0] |> List.map ((+) 1)) = [1 + 3..1 + 0]
[4; 3; 2; 1] = [4..1]
[4; 3; 2; 1] = []
false
C:\File.fs(28,0): at Module.demo Unquote xUnit support()
FsUnit and Unquote have similar missions: to allow you to write tests in an idiomatic way, and to produce informative failure messages. But FsUnit is really just a small wrapper around NUnit Constraints, creating a DSL which hides object construction behind composable function calls. But it comes at a cost: you lose static type checking in your assertions. For example, the following is valid in FsUnit
[<Test>]
let test1 () =
1 |> should not (equal "2")
But with Unquote, you get all of F#'s static type-checking features so the equivalent assertion would not even compile, preventing us from introducing a bug in our test code
[<Test>] //yes, Unquote supports both xUnit and NUnit automatically
let test2 () =
test <# 1 <> "2" #> //simple assertions may be written more concisely, e.g. 1 <>! "2"
// ^^^
//Error 22 This expression was expected to have type int but here has type string
Also, since quotations are able to capture more information at compile time about an assertion expression, failure messages are a lot richer too. For example the failing FsUnit assertion 1 |> should not (equal 1) produces the message
Test 'Test.Swensen.Unquote.VerifyNunitSupport.test1' failed:
Expected: not 1
But was: 1
C:\Users\Stephen\Documents\Visual Studio 2010\Projects\Unquote\VerifyNunitSupport\FsUnit.fs(11,0): at FsUnit.should[a,a](FSharpFunc`2 f, a x, Object y)
C:\Users\Stephen\Documents\Visual Studio 2010\Projects\Unquote\VerifyNunitSupport\VerifyNunitSupport.fs(29,0): at Test.Swensen.Unquote.VerifyNunitSupport.test1()
Whereas the failing Unquote assertion 1 <>! 1 produces the following failure message (notice the cleaner stack trace too)
Test 'Test.Swensen.Unquote.VerifyNunitSupport.test1' failed:
1 <> 1
false
C:\Users\Stephen\Documents\Visual Studio 2010\Projects\Unquote\VerifyNunitSupport\VerifyNunitSupport.fs(29,0): at Test.Swensen.Unquote.VerifyNunitSupport.test1()
And of course from my first example at the beginning of this answer, you can see just how rich and complex Unquote expressions and failure messages can get.
Another major benefit of using plain F# expressions as test assertions over the FsUnit DSL, is that it fits very well with the F# process of developing unit tests. I think a lot of F# developers start by developing and testing code with the assistance of FSI. Hence, it is very easy to go from ad-hoc FSI tests to formal tests. In fact, in addition to special support for xUnit and NUnit (though any exception-based unit testing framework is supported as well), all Unquote operators work within FSI sessions too.
I haven't yet tried Unquote, but I feel I have to mention FsCheck:
http://fscheck.codeplex.com/
This is a port of Haskells QuickCheck library, where rather than specifying what specific tests to carry out, you specify what properties about your function should hold true.
To me, this is a bit harder than using traditional tests, but once you figure out the properties, you'll have more solid tests. Do read the introduction: http://fscheck.codeplex.com/wikipage?title=QuickStart&referringTitle=Home
I'd guess a mix of FsCheck and Unquote would be ideal.
You could try my unit testing library Expecto; it's has some features you might like:
F# syntax throughout, tests as values; write plain F# to generate tests
Use the built-in Expect module, or an external lib like Unquote for assertions
Parallel tests by default
Test your Hopac code or your Async code; Expecto is async throughout
Pluggable logging and metrics via Logary Facade; easily write adapters for build systems, or use the timing mechanism for building an InfluxDB+Grafana dashboard of your tests' execution times
Built in support for BenchmarkDotNet
Build in support for FsCheck; makes it easy to build tests with generated/random data or building invariant-models of your object's/actor's state space
Hello world looks like this
open Expecto
let tests =
test "A simple test" {
let subject = "Hello World"
Expect.equal subject "Hello World" "The strings should equal"
}
[<EntryPoint>]
let main args =
runTestsWithArgs defaultConfig args tests

How to handle unit tests in F#?

How do you create unit tests in F#? I typically use the UnitTest portion of Visual Studio with a [TestClass] and [TestMethod] attributes and use the Test View to run these. I know I can just create a script file and run these, but I like the way that it is currently handled.
Check out fscheck. It's a port of Haskell's Quickcheck. Fscheck allows you to specify properties a function must satisfy which it will then verify against a "large number of randomly generated cases".
It's something you can't easily do with an imperative language like C#.
I'd rather use FsUnit or FsTest to write tests in F#, it feels more natural than OO xUnit style tests.
EDIT 2014: I now consider FsUnit/FsTest to be mostly useless syntax sugar. And "more natural than OO" doesn't mean absolutely anything. A few months ago I wrote my current thoughts on testing here (I recommend reading the entire thread).
In VS2013 you can use the below.
open Microsoft.VisualStudio.TestTools.UnitTesting
[<TestClass>]
type testrun() =
[<TestInitialize>]
member x.setup() =
//your setup code
[<TestMethod>]
member x.yourTestName() =
//your test code
Hint: If you are looking for UI unit testing then you can use this setup with Canopy.
I use a combination of xUnit.net, TestDriven.Net (Visual Studio Add-in for running tests, free for "students, open source developers and trial users"), and my own open source Unquote library (which also works with NUnit and any other exception-based assertion framework). This has worked out great and getting started is really easy:
Download and install TestDriven.Net
Download xUnit.net, unzip to any location and run xunit.installer.exe to integrate with TestDriven.Net
Download Unquote, unzip to any location
Create a project within your solution for unit tests
Add references to xunit.dll and Unquote.dll (from unzipped downloads) in your unit test project
The following is a simple example of a .fs file in the unit test project containing xUnit.net / Unquote style unit tests.
module Tests
open Swensen.Unquote
open Xunit
[<Fact>]
let ``description of first unit test`` () =
test <# (11 + 3) / 2 = String.length ("hello world".Substring(4, 5)) #>
[<Fact>]
let ``description of second unit test`` () =
let x = List.rev [1;2;3;4]
x =? [4;3;1;2]
Run all the unit tests in the project by right-clicking the project in the solution explorer and selecting Run Test(s). Both of the previous example tests will fail with the following printed to the Visual Studio Output window:
------ Test started: Assembly: Tests.dll ------
Test 'Tests.description of second unit test' failed:
[4; 3; 2; 1] = [4; 3; 1; 2]
false
C:\Solution\Project\Tests.fs(12,0): at Tests.description of second unit test()
Test 'Tests.description of first unit test' failed:
(11 + 3) / 2 = String.length ("hello world".Substring(4, 5))
14 / 2 = String.length "o wor"
7 = 5
false
C:\Solution\Project\Tests.fs(7,0): at Tests.description of first unit test()
0 passed, 2 failed, 0 skipped, took 1.09 seconds (xUnit.net 1.7.0 build 1540).
You might want to try NaturalSpec. It's a F# UnitTest-Framework on top of NUnit.
Try XUnit.net
As of version 2.5, NUnit allows you to use static members as tests. Also, the class-level TestFixtureAttribute is only necessary for generic or classes with non-default constructors. NUnit also has a backward-compatible convention that a test member may start with the word "test" instead of using TestAttribute, so you can almost write idiomatic F# with NUnit > 2.5.
Update
You can see some test examples without the TestFixtureAttribute in the Cashel library. I continued using the TestAttribute since it appears few test runners correctly pick up tests when it is not present, so that part of the NUnit post may be incorrect or at least misleading.