2011-08-19 70 views
6

如何在OCaml中有一个假的数据库连接的测试加倍?在OCaml中做一个测试加倍

假设您想要在数据库之上测试一个小型API,并且其工作方式是通过为API公开的每个函数提供Connection类型。

喜欢的东西:

let get_data connection = do_something_with_connection 

这将如何进行单元测试?

更大的意义在于OCaml通常会进行这种测试,因为OCaml的强大类型系统已经确保您不会犯错误错误?

回答

3

您将创建一个对象,它具有与Connection相同的方法名称,每个对象都具有相同的签名(显然具有存根功能)。然后你可以实例化这些对象中的一个,并通过子类型声明它是一个Connection。然后它可以被传入任何函数。

Here对子类型(应该指出,与Ocaml中的继承不同)有帮助。

1

用一个仿函数构建你的模块,该函数以连接模块为参数。然后,您可以在测试中将连接模块剔除。

因此,举例来说,你db.ml文件可能看起来有点像这样:

(* The interface of Connection that we use *)                          
module type CONNECTION = sig 
    type t 
    val execute : string -> t -> string list 
end 

(* functor to build Db modules, given a Connection module *) 
module Make(Connection : CONNECTION) = struct 
    ... 
    let get_data connection = 
    do_something_with (Connection.execute "some query" connection) 
    ... 
end 

然后在你的test_db.ml你可以存根出连接模块

let test_get_data() = 
    let module TestConnection = struct 
    type t = unit 
    let execute _ _ = ["data"] 
    end in 
    let module TestDb = Db.Make(TestConnection) in 

    assert (TestDb.get_data() = ["munged data"])