Performing a double test in OCaml

What is the usual way to have a double test in OCaml that fakes a database connection?

Suppose you want to test a small API on top of a database and how it works, providing a Connection type for each function provided by the API.

Sort of:

 let get_data connection = do_something_with_connection 

How will this be tested?

On a big note, is this normal OCaml testing, given the fact that a powerful OCaml type system is already sure that you are not making strange mistakes?

+6
source share
2 answers

You must create an object that has all the same method names as Connection, with the same signature (and, obviously, using the stub function). You can then instantiate one of these objects and declare it as a connection through subtyping. Then it can be transferred to any of the functions.

Here is a useful bit about subtyping (which, it should be noted, is not the same as inheritance in Ocaml).

+3
source

Create your module using a functor that takes a Connection module as an argument. Then you can stub the Connection module in your tests.

So, for example, your db.ml file might look something like this:

 (* 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 

Then in your test_db.ml you can just close the Connection module

 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"]) 
+1
source

Source: https://habr.com/ru/post/895439/


All Articles