简体   繁体   中英

OUnit: assert value is instance of type

Using the OUnit unit testing framework in OCaml, I would like to test that the result of evaluating a function is an instance of a specified type.

Defining such a test in Python's PyTest would be done as follows:

def test_foo():
    assert isinstance(foo(2), int)

How can this logic be translated to OUnit? That is, how are assertions of type membership specified?

I'm aware that, assuming the function under test is annotated with the proper type signature, this testing might be unnecessary.

This is the job of a type checker, and it is made automatically during the compilation (at static time). The type checker (ie, the compiler) guarantees that all values that are created by a function has the same type, and the type is defined statically at the compilation time. You will not be able to compile a function, that creates values of different types, as you will get a type error during the compilation. This is an essential property of all statically typed languages, eg, Java, C and C++ also has the same property.

So, probably, you're using are confusing terminology. It might be the case, that what you're actually trying to test, is that the value belongs to a particular variant of a sum type. For example, if you have a sum type called numbers defined as:

type t = 
  | Float of float
  | Int of int

and you would like to test that function truncate , defined as

 let truncate = function
   | Float x -> Int (truncate x)
   | x -> x

always returns the Int variant, then you can do this as follows:

  let is_float = function Float _ -> true | _ -> false
  let is_int = function Int _ -> true | _ -> false

  assert (is_int (truncate 3.14))

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