我想單元測試一個返回Result
(見下文)的函數。如何比較深層嵌套的歧視聯盟?
我的問題是:我怎樣才能輕鬆地檢查結果在數值上等於預期值?
下面是與精確匹配的版本。
type QuadraticResult =
| ComplexResult of Complex * Complex
| DoubleResult of float
| TwoResults of float * float
type Result=
| QuadraticResult of QuadraticResult
| LinearResult of LinearFormulaSolver.Result
/// Solves a x² + bx + c = 0
let Compute (a,b,c) : Result =
[<Fact>]
member test.``the solution for x² = 0.0 is a double 0.0``()=
let result = Compute (1.0, 0.0, 0.0)
let expected = Result.QuadraticResult (DoubleResult 0.0)
// only exact match, I'd like to test if difference is below a certain threshold
Assert.Equal (result, expected)
這是我迄今使用的解決方案。 它基於Andreys解決方案,但是擴展了允許的距離,結果排列和線性情況。 :
let ComplexEquality distance (x : Complex) (y : Complex)=
let dx = x.Real - y.Real
let dy = x.Imaginary - y.Imaginary
abs (dx) < distance && abs(dy) < distance
let QuadraticEquality distance x y = match (x,y) with
| (ComplexResult (a,b),ComplexResult(c,d)) -> (ComplexEquality distance a c && ComplexEquality distance b d) || (ComplexEquality distance a d && ComplexEquality distance b c)
| (DoubleResult a,DoubleResult b) -> abs (a - b) < distance
| (TwoResults (a,b),TwoResults(c,d)) -> (abs(a - c) < distance && (b - d) < distance) || (abs(a - d) < distance && (b - c) < distance)
| _ -> false
let LinearEquality distance x y = match (x , y) with
| (SingleResult a, SingleResult b) -> abs (a-b) < distance
| (NoResults, NoResults) | (InfiniteResults, InfiniteResults) -> true
| _ -> false
let ResultEquality distance x y = match (x,y) with
| (QuadraticResult a,QuadraticResult b) -> QuadraticEquality distance a b
| (LinearResult a,LinearResult b) -> LinearEquality distance a b
| _ -> false
[<Fact>]
member test.``the solution for x² = 0 is a double 0``()=
let result = QuadraticFormulaSolver.Compute (1.0, 0.0, 0.0)
let expected = Result.QuadraticResult (QuadraticFormulaSolver.DoubleResult 0.00001)
Assert.True(ResultEquality 0.001 result expected)
我現在正在使用包含在我的問題中的解決方案的增強版本。 – Onur