A unit test is a small piece of code written by a developer to verify that a small, well-defined function of the measured code is correct. Typically, a unit test (use case) is used to determine the behavior of a particular function under a particular condition (or scene). If you want to learn more about the benefits of unit testing, you can look at the unit test combat.
In the. NET community, NUnit is undoubtedly the most Classic unit test tool, and to understand its usage, it is advisable to look at a great article in the garden NUnit the detailed use method. This article does not dwell on this. In addition Mbunit as an up-and-comer, it is also worth a try.
In F #, LOP (language-oriented programming) is one of its bright spots, while fsunit is a good practice for LOP. Fsunit uses F # development, the tests that are written with it are close to the natural language (English), where we can see the power of F # 's combination of functions.
In this article, I will introduce the basic usage of NUnit and fsunit, respectively, with a simple example. Suppose we are developing a class library myfslib, which has a module mathhelper, which has some functions about mathematics, and now it's about testing these functions. The code for Mathhelper is as follows:
Signature of F # Code-mathhelper
#light
Module Myfslib.mathhelper
Gets the square value of a floating-point number
Val square:float-> Float
Gets the cubic value of a floating-point number
Val cube:float-> Float
To determine whether an integer is an even
Val Iseven:int-> BOOL
To determine whether an integer is odd
Val Isodd:int-> BOOL
Gets an array of prime numbers that are not greater than the specified positive integer
Val generateprimes:int-> int array
Implementation of F # Code-mathhelper
#light
Module Myfslib.mathhelper
Open System
Let pow x y = Math.pow (x, y)
Let square x = POW x 2.0
Let cube x = Pow x 3.0
Let IsEven x = x% 2 = 0
Let isodd x = x% 2 = 1
Eratosthenes Sieve method
Let generateprimes n =
Match n with
| _ When n < 2-> [| |]
| _->
Init sieve.
Let sieve = [| For i in 0 ... n do yield true |]
Let IsPrime index = sieve. [Index]
Check it.
Let Upperbound = Convert.ToInt32 (Math.sqrt ((float) n))
For i = 2 to Upperbound do
If IsPrime I then
For j in [I * 2 ... sieve. LENGTH-1] Do
Sieve. [j] <-False
Let mutable count = 0
For i = 2 to sieve. Length-1 do
If IsPrime I then
Count <-Count + 1
Let primes = array.create count 0
Let mutable index = 0
For i = 2 to sieve. Length-1 do
If IsPrime I then
Primes. [Index] <-I
Index <-Index + 1
Primes