unit testing - property-based-test for simple object validation -


consider simple example:

  • theres person object
  • it must have 1 of: firstname , lastname (or both, 1 mandatory)
  • it must have valid age (integer, between 0 , 150)

how property-base-test simple case?

i don't think can meaningfully answer question in language-agnostic way, overall design approach entirely depend on capabilities of language in question.

for example, in languages strong static types , sum types, of above requirements can modelled declaratively using type system. here's f# example:

type name = | firstname of string | lastname of string | fullname of string * string 

this name type can contain either first name, or last name, or both. it's not possible create values don't follow requirements.

the case constructor of following age type can hidden putting type in separate module. if module exports toage (and getage) function below, way create age value call toage.

type age = age of int  let toage x =     if 0 <= x && x <= 150     (age x)     else none  let getage (age x) = x 

using these auxiliary types, can define person type:

type person = { name : name; age : age } 

most of requirements embedded in type system. can't create invalid value of person type.

the behaviour can fail contained in toage function, that's behaviour can meaningfully subject property-based testing. here's example using fscheck:

open system open fscheck open fscheck.xunit open swensen.unquote  [<property(quietonsuccess = true)>] let ``value in valid age range can turned age value`` () =     prop.forall (gen.choose(0, 150) |> arb.fromgen) (fun ->         let actual = toage         test <@ actual |> option.map getage |> option.exists ((=) i) @>)  [<property(quietonsuccess = true)>] let ``value in invalid age range can't turned age value`` () =     let toolow = gen.choose(int32.minvalue, -1)     let toohigh = gen.choose(151, int32.maxvalue)     let invalid = gen.oneof [toolow; toohigh] |> arb.fromgen     prop.forall invalid (fun ->          let actual = toage          test <@ actual |> option.isnone @>) 

as can tell, tests 2 cases: valid input values, , invalid input values. defining generators each of cases, , verifying actual values.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -