比较歧视联盟 [英] Comparing Discriminated Unions
问题描述
我是F#的新手,并且正在使用FParsec.我将使用FParsec生成AST.我想使用FsUnit围绕解析器的各个部分编写一些测试,以确保正确的操作.
I'm a newbie to F# and I'm playing around with FParsec. I would use FParsec to generate an AST. I would like to use FsUnit to write some tests around the various parts of the parser to ensure correct operation.
我在语法上有点麻烦(对不起,确切的代码在起作用,我可以稍后再发布一个特定的示例),那么一个人如何比较两个有区别的并集(一个是期望的,另一个是实际的)结果)?有人可以使用FsUnit(或NUnit)提供一个很小的代码示例吗?
I'm having a bit of trouble with the syntax (sorry, the exact code is at work, I can post a specific example later) so how exactly could one compare two discriminated unions (one the expected, the other the actual result)? Could someone provide a tiny code example using FsUnit (or NUnit), please?
歧视工会的例子(非常简单)
An example discriminated union (very simple)
type AST =
| Variable of string
| Class of string
| Number of int
推荐答案
正如Brian所指出的那样,F#联合具有结构相等性,因此无论您喜欢使用哪种单元测试框架,都可以轻松实现.
Since, as Brian pointed out, F# unions have structural equality, this is easy using whichever unit testing framework you are fond of.
FsUnit是在NUnit之上构建的特定于F#的库.我个人最喜欢的F#特定单元测试库是取消引用 ;;),该框架与框架无关,与NUnit,xUnit.net,MbUnit甚至在FSI内都可以很好地工作.您可能会对此与以下内容的比较感兴趣FsUnit.
FsUnit is an F# specific library built on top of NUnit. My personal favorite F# specific unit testing library is Unquote, ;), which is framework agnostic, working very well with NUnit, xUnit.net, MbUnit, ... or even within FSI. You may be interested in this comparison with FsUnit.
那么,您将如何使用NUnit + Unquote来做到这一点?这是一个完整的工作示例:
So, how would you do this with NUnit + Unquote? Here's a full working example:
module UnitTests
open NUnit.Framework
open Swensen.Unquote
type AST =
| Variable of string
| Class of string
| Number of int
let mockFParsec_parseVariable input = Variable(input)
[<Test>]
let ``test variable parse, passing example`` () =
test <@ mockFParsec_parseVariable "x" = Variable("x") @>
[<Test>]
let ``test variable parse, failing example`` () =
test <@ mockFParsec_parseVariable "y" = Variable("x") @>
然后使用TestDriven.NET运行测试,输出如下:
Then running the tests using TestDriven.NET, the output is as follows:
------ Test started: Assembly: xxx.exe ------
Test 'UnitTests.test variable parse, failing example' failed:
UnitTests.mockFParsec_parseVariable "y" = Variable("x")
Variable "y" = Variable("x")
false
C:\xxx\UnitTests.fs(19,0): at UnitTests.test variable parse, failing example()
1 passed, 1 failed, 0 skipped, took 0.80 seconds (NUnit 2.5.10).
这篇关于比较歧视联盟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!