[英]How to check if an Exception is thrown by a method with xUnit and FsCheck in F#
我正在用C#用xUnit和FsCheck在F#中编写测试来在C#中做Diamond Kata,在尝试检查是否在用户输入无效的情况下抛出异常(任何不是'char'的字符)时遇到了一些麻烦。 t没有任何变音符号的字母)。 现在的代码如下所示:
被测试的方法:
public static string Make(char letter)
{
if (!Regex.IsMatch(letter.ToString(), @"[a-zA-Z]"))
{
throw new InvalidOperationException();
}
// code that makes the diamond
}
考试:
[<Property>]
let ``Diamond.Make must throw an InvalidOperationException if a character that isn't
an alphabet letter without any diacritics is given`` (letter : char) =
(not (('A' <= letter && letter <= 'Z') || ('a' <= letter && letter <= 'z'))) ==> lazy
(Assert.Throws<InvalidOperationException>(fun () -> Diamond.Make letter |> ignore))
我的方法的问题在于,测试表明没有引发异常,但是当我使用测试套件显示的输入来运行应用程序时,就会引发异常。
这是测试套件给出的消息(我故意省略了测试名称和堆栈跟踪):
Test Outcome: Failed
Test Duration: 0:00:00,066
Result Message:
FsCheck.Xunit.PropertyFailedException :
Falsifiable, after 1 test (0 shrinks) (StdGen (1154779780,296216747)):
Original:
')'
---- Assert.Throws() Failure
Expected: typeof(System.InvalidOperationException)
Actual: (No exception was thrown)
尽管测试套件说对于值')'
不会引发任何异常,但是我对其进行了手动测试,并且确实引发了预期的异常。
如何确保测试捕获到异常?
我认为问题在于,如果发生Assert.Throws返回给定类型的异常。 只是忽略Assert的返回值。
let test (letter : char) =
(not (('A' <= letter && letter <= 'Z') || ('a' <= letter && letter <= 'z'))) ==>
lazy
Assert.Throws<InvalidOperationException>(fun () -> Diamond.Make letter |> ignore)
|> ignore
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.