gpt4 book ai didi

unit-testing - 如何使用 f# 编写带有模拟的测试

转载 作者:行者123 更新时间:2023-12-04 03:58:38 24 4
gpt4 key购买 nike

我想用模拟对象编写 F# 单元测试。我正在使用 NUnit。
但不幸的是我找不到任何例子。

以下是被测代码的示例:

type ICustomer = interface
abstract Id: int with get
abstract Name: string with get
abstract CalculateBalanceWithDiscount: decimal -> decimal
end

type Customer = class
val id: int
val name: string
val balance: decimal
new(id, name, balance) =
{id = id; name = name; balance = balance}
interface ICustomer with
member this.Id
with get () = this.id
member this.Name
with get () = this.name
member this.CalculateBalanceWithDiscount discount =
this.balance - (discount * this.balance)
end
end

最佳答案

作为旁注,您可以使用隐式构造函数语法使类声明更好一点。您还可以简化只读属性,因为您可以省略 with get() :

// F# infers that the type is an interface
type ICustomer =
abstract Id : int
abstract Name : string
abstract CalculateBalanceWithDiscount : decimal -> decimal

// Parameters of the implicit constructor are autoamtically
// accessible in the body (they are stored as fields)
type Customer(id:int, name:string, balance:decimal) =
interface ICustomer with
member this.Id = id
member this.Name = name
member this.CalculateBalanceWithDiscount(discount) =
balance - (discount * balance)

关于测试 - 你有什么你想要实现的例子吗?我相信我们可以帮助例如从 C# 翻译代码。或者您想使用模拟编写什么样的测试?

一般来说,F# 和函数式语言的一个好处是您通常可以更轻松地测试代码,而无需使用任何模拟。函数式程序以不同的风格编写:

In functional programming, a function takes all it's inputs as arguments and the only thing that it does is that it calculates and returns some result. This is also true for methods of immutable object types - they do not modify any state of any objects



模拟通常用于两个目的:
  • 验证测试操作是否执行了对引用对象的方法的调用,例如prod.Update(newPrice) 更新对象的状态。但是,在函数式编程中,该方法应该返回新状态作为结果 - 因此您不需要模拟对象。只需检查新返回的状态是否符合您的预期。
  • 加载创建应用程序的假组件,例如而不是从数据库加载数据。同样,纯函数式函数应该将所有输入作为参数。这意味着您不需要创建模拟对象 - 您只需使用一些测试数据作为参数调用函数(而不是从数据库加载的数据)。

  • 总之,这意味着在设计良好的函数式程序中,您应该能够将所有单元测试简单地编写为检查,以验证某些函数是否返回预期参数的预期结果。当然,这在 F# 中并非严格正确,因为您可能需要与其他不纯的 .NET 组件进行互操作(但只有提供更具体的示例才能回答这个问题)。

    关于unit-testing - 如何使用 f# 编写带有模拟的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2537200/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com