使用 FsCheck 属性时如何排除空值? [英] How to exclude null value when using FsCheck Property attribute?
问题描述
我需要编写一个简单的方法来接收一个参数(例如一个 string
)并执行 smth.通常我最终会进行两次测试.第一个是保护条款.第二个将验证预期行为(为简单起见,该方法不应失败):
I need to write a simple method that receives a parameter (e.g. a string
) and does smth. Usually I'd end up with two tests. The first one would be a guard clause. The second would validate the expected behavior (for simplicity, the method shouldn't fail):
[Fact]
public void DoSmth_WithNull_Throws()
{
var sut = new Sut();
Assert.Throws<ArgumentNullException>(() =>
sut.DoSmth(null));
}
[Fact]
public void DoSmth_WithValidString_DoesNotThrow()
{
var s = "123";
var sut = new Sut();
sut.DoSmth(s); // does not throw
}
public class Sut
{
public void DoSmth(string s)
{
if (s == null)
throw new ArgumentNullException();
// do smth important here
}
}
当我尝试使用 FsCheck [Property]
属性来生成随机数据,null
和许多其他随机值被传递给测试,这在某些时候会导致 NRE:
When I try to utilize the FsCheck [Property]
attribute to generate random data, null
and numerous other random values are passed to the test which at some point causes NRE:
[Property]
public void DoSmth_WithValidString_DoesNotThrow(string s)
{
var sut = new Sut();
sut.DoSmth(s); // throws ArgumentNullException after 'x' tests
}
我意识到这就是 FsCheck 生成大量随机数据以涵盖不同情况的全部想法,这绝对是很棒的.
I realize that this is the entire idea of FsCheck to generate numerous random data to cover different cases which is definitely great.
是否有任何优雅的方法来配置 [Property]
属性以排除不需要的值?(在这个特定的测试中,null
).
Is there any elegant way to configure the [Property]
attribute to exclude undesired values? (In this particular test that's null
).
推荐答案
FsCheck 有一些内置类型,可用于指示特定行为,例如,引用类型值不应为 null.其中之一是NonNull<'a>
.如果您要求其中之一,而不是要求原始字符串,您将不会得到空值.
FsCheck has some built-in types that can be used to signal specific behaviour, like, for example, that reference type values shouldn't be null. One of these is NonNull<'a>
. If you ask for one of these, instead of asking for a raw string, you'll get no nulls.
在 F# 中,您可以将其分解为函数参数:
In F#, you'd be able to destructure it as a function argument:
[<Property>]
let DoSmth_WithValidString_DoesNotThrow (NonNull s) = // s is already a string here...
let sut = Sut ()
sut.DoSmth s // Use your favourite assertion library here...
}
我认为在 C# 中,它应该看起来像这样,但我还没有尝试过:
I think that in C#, it ought to look something like this, but I haven't tried:
[Property]
public void DoSmth_WithValidString_DoesNotThrow(NonNull<string> s)
{
var sut = new Sut();
sut.DoSmth(s.Get); // throws ArgumentNullException after 'x' tests
}
这篇关于使用 FsCheck 属性时如何排除空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!