使用List.map应抛出异常

时间:2015-11-06 16:38:22

标签: f# functional-programming nunit functional-testing

let d5=["IIII";"VVVV";"XXXX";"LLLL";"MMMM"] 

[<Test; ExpectedException(typeof<System.Exception>)>]
    member this.
        ``More than 3 times repetive characters `` ()=
        //Missing part

此测试无效。 我有转换器解析罗马数字。但它的工作原理错误

  

[ “IIII”, “VVVV”; “XXXX”, “LLLL”; “MMMM”]

当您发送转换(“IIII”)时,它返回4,但它应该给出System.Exception错误。我需要编写NUnit测试(不是修复转换器),它会映射列表中的每个字符串,并在每个字符串返回错误时传递。否则失败。 我想写的测试如下:

d5=["IIII";"VVVV";"XXXX";"LLLL";"MMMM"]
convert each d5 element
if each of them is giving system.exception error 
then test is successfull
else test is failed

任何解决方案?任何的想法。 。 如果您有兴趣,转换方法就在这里Convert Method

2 个答案:

答案 0 :(得分:2)

您可以使用TestCase属性来参数化测试,并使用Assert.Throws来验证是否抛出了异常:

open System
open NUnit.Framework

[<TestFixture>]
type Tests() =

    [<TestCase("IIII")>]
    [<TestCase("VVVV")>]
    [<TestCase("XXXX")>]
    [<TestCase("LLLL")>]
    [<TestCase("MMMM")>]
    member this.ThrowsOnInvalidInput (cand : string) =
        Assert.Throws<Exception> (fun () -> convert cand |> ignore) |> ignore

答案 1 :(得分:1)

您想要的是分别测试所有值:

open NUnit.Framework
open FsUnit

type ConvertTest() = 

    let convert s = 
        if String.length s > 3 then failwith "Something's wrong"
        else String.length s

    [<Theory>]
    member this.``More than 3 characters throws``([<Values("IIII", "VVVVVV", "XXXX", "LLLL", "MMMM")>] s) = 
        (fun () -> convert s |> ignore) |> should throw typeof<System.Exception>

    [<Theory>]
    member this.``Less than 4 characters returns length``([<Values("II", "VV", "XXX", "LLL", "MMM")>] s) = 
        convert s |> should equal s.Length

我故意将convert方法改为稍微不同的实现(因为你没有给出)但是应该很明显如何继续。