如何使用F#区分的联合类型作为TestCase属性参数? [英] How can I use an F# discriminated union type as a TestCase attribute parameter?

查看:95
本文介绍了如何使用F#区分的联合类型作为TestCase属性参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试F#函数的返回结果是否与预期的已区分联合案例相符.我正在使用NUnit创建测试,它不喜欢区分联合类型作为TestCase参数.以下测试用例无法编译:

I am trying to test that the return result from an F# function matches an expected discriminated union case. I am using NUnit to create the tests and it does not like the discriminated union type as a TestCase parameter. The following test case fails to compile:

[<TestCase("RF000123", Iccm.CallType.Request)>]
let ``callTypeFromCallNumber returns expected call type``
    callNumber callType =
    test <@ Iccm.callTypeFromCallNumber callNumber = callType @>

我希望这是NUnit的局限性,但我不确定.我有一个解决此问题的方法,我将其发布为答案,但是更优雅的解决方案将是不错的选择.

I expect that this is a limitation of NUnit but I am not completely sure. I have an idea to work around this which I will post as my answer but a more elegant solution will be nice.

如何使用已区分的联合用例作为测试用例属性参数?

How can I use a discriminated union case as a test case attribute parameter?

推荐答案

这不是NUnit的限制,而是F#语言(以及C#和VB)的限制:您只能放置常量转换为属性,但不转换为对象.区分的联合会编译为IL中的对象,因此您不能将它们放入属性中.

This isn't a limitation of NUnit, but of the F# language (as well as C# and VB): You can only put constants into attributes, but not objects. Discriminated Unions compile to objects in IL, so you can't put them into attributes.

可以将枚举放入属性中,因为它们是常量(它们在运行时是数字).

You can put enums into attributes, though, since they're constants (they're numbers at run-time).

从OP中的示例来看,CallType歧视联盟似乎没有相关数据,因此您可以考虑将设计更改为

From the example in the OP, it looks like the CallType Discriminated Union has no associated data, so you could consider changing the design to an enum instead:

type CallType =
    | Request = 0
    | Incident = 1
    | ChangeManagement = 2
    | Unknown = 3

但是,您应该意识到,这使CallType成为枚举;它不再是歧视联盟.不过,它应该使您能够使用属性中的值.

You should realise, though, that that makes CallType an enum; it's no longer a Discriminated Union. It should enable you to use the values in attributes, though.

这篇关于如何使用F#区分的联合类型作为TestCase属性参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆