单元测试 – 如何在F#中打破函数依赖?

前端之家收集整理的这篇文章主要介绍了单元测试 – 如何在F#中打破函数依赖?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在不调用fun2的情况下对fun1进行单元测试.

let fun2() =
    // Some complex function with lots of dependencies.
    1

let fun1() =
    fun2() * 2

打破两个函数之间依赖关系的最佳方法是什么?

我尝试了几种不同的方法,但它们只是增加了混乱.

将fun2传递给fun1

let fun1(fun2) =
    fun2() * 2

转换为类并覆盖

type FunClass() =
    abstract member fun2 : unit -> int
    default x.fun2() = 1

    member x.fun1() =
        x.fun2() * 2

type FunClassMock() =
    override member x.fun2() = 1

使用状态模式

type Fun1Class(fun2Class) =

    member x.fun1() =
       fun2Class.fun2() * 2

使用变量

let fun2Imp() =
    1

let mutable fun2 = fun2Imp

let fun1() =
    fun2() * 2

有更干净的方式吗?

解决方法

这取决于您的用法,但您可以这样做:

let fun2() =
    // Some complex function with lots of dependencies.
    1

let createFun1 fun2 =
    fun () -> fun2() * 2

let fun1 = createFun1 fun2

这对于单元测试也很有用,因为你可以通过简单地为fun2传递一个简单的函数来测试fun1.

猜你在找的设计模式相关文章