简体   繁体   中英

OCaml mock module generation

We have quite some ocaml code with lots of hard coupled dependencies between modules. Lately, we've been moving to the functor approach to decouple those modules, so if we have module A that depends on module B and C, we go like this in the declaration :

module A: (B:B_Signature) (C:C_Signature) = struct ... end

Like this we can inject a 'mocked up' B or C module, answering those signatures, in module A for unit testing, and can still create the production module with the real B and C modules in it. The problem is that right now we have to type these mocked up modules out by hand, which is a bit of a blocker, as it's usually loads of boilerplate.

So, I'm looking for a way to generate 'mock' modules from an ocaml module, instead of typing them out by hand. What I mean with that is if I have a module with a few functions, having the following signature

   module type A =
    sig
    val f: string -> int -> string
    val g: string -> string -> int
    end

I would like to generate a mock implementation, for example like this

module A_mock =
struct
let f _s _i =
    ""
let g _s1 _s2 =
    0
end

So, this is a module that has both functions, with the same signature, but with implementations of f and g that ignore their arguments and return by default and empty string for function f and 0 for function g.

Those default values, empty string and zero, are just an example. I know that I will want to have this more configurable in the end, I want to create the mock and specify the return values for certain functions, maybe even be able to inspect the arguments with which the mocked functions were called and so on, but for now, for this simple case, I'm looking for a solution other than typing and implementing this all by hand.

I didn't find any frameworks that do this for OCaml.

I was trying to find out how do this maybe through camlp4 and code generation but the documentation seems to be kind of limited and I didn't really see whether it would even be possible.

So, my question, does anybody know of a framework or whether there is a code generation kind of way to create this kind of boilerplate modules from a signature in OCaml?

Kasper

Okay, I created the start of a camp4 library that would create a mock module. There's a wiki page on the github with a bit of explanation, and an example signature file and two scripts checked in on the master branch as well for now. Hope to be able to expand this and make it more robust in time, when we start using it more we'll likely get ideas about it as well.

https://github.com/KasperJanssens/mockaml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM