6 people like it.
Like the snippet!
Mocking library
F# Mocking library with a fluent interface Moq users should find familiar. Generate mocks for interfaces and abstract types. Supports mocking methods, properties and events. Specify arguments as wildcards or values to match. Define results as values, computed values or exceptions.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
|
/// Generic mock type over abstract types and interfaces
type Mock<'TAbstract when 'TAbstract : not struct> internal (calls) =
/// Abstract type
let abstractType = typeof<'TAbstract>
/// Converts argument expressions to Arg array
let toArgs args =
let hasAttribute a (mi:MethodInfo) = mi.GetCustomAttributes(a, true).Length > 0
[|for arg in args ->
match arg with
| Value(v,t) | Coerce(Value(v,t),_) -> Arg(v)
| PropertyGet(None, pi, []) -> pi.GetValue(null, [||]) |> Arg
| Call(_, mi, _) when hasAttribute typeof<WildcardAttribute> mi -> Any
| _ -> raise <| NotSupportedException(arg.ToString()) |]
/// Converts expression to a tuple of MethodInfo and Arg array
let toCall = function
| Call(Some(x), mi, args) when x.Type = abstractType ->
mi, toArgs args
| PropertyGet(Some(x), pi, args) when x.Type = abstractType ->
pi.GetGetMethod(), toArgs args
| PropertySet(Some(x), pi, args, value) when x.Type = abstractType ->
pi.GetSetMethod(), toArgs args
| expr -> raise <| NotSupportedException(expr.ToString())
/// Converts expression to corresponding event Add and Remove handlers
let toHandlers = function
| Call(None, mi, [Lambda(_,Call(Some(x),addHandler,_));
Lambda(_,Call(Some(_),removeHandler,_));_])
when x.Type = abstractType ->
addHandler, removeHandler
| expr -> raise <| NotSupportedException(expr.ToString())
/// Constructs mock builder
new () = Mock([])
/// Specifies a method or property of the abstract type as a quotation
member this.Setup(f:'TAbstract -> Expr<'TReturnValue>) =
let default' = Unchecked.defaultof<'TAbstract>
let call = toCall (f default')
ResultBuilder<'TAbstract,'TReturnValue>(call,calls)
/// Specifies an event of the abstract type as a quotation
member this.SetupEvent(f:'TAbstract -> Expr<'TEvent>) =
let default' = Unchecked.defaultof<'TAbstract>
let handlers = toHandlers (f default')
EventBuilder<'TAbstract,'TEvent>(handlers,calls)
/// Creates an instance of the abstract type
member this.Create() = mock<'TAbstract>(calls)
/// Generic builder for specifying method or property results
and ResultBuilder<'TAbstract,'TReturnValue when 'TAbstract : not struct>
internal (call, calls) =
let mi, args = call
/// Specifies the return value of a method or property
member this.Returns(value:'TReturnValue) =
let result =
if typeof<'TReturnValue> = typeof<unit> then Unit
else ReturnValue(value)
Mock<'TAbstract>((mi, (args, result))::calls)
/// Specifies a computed return value of a method or property
member this.Returns(f:unit -> 'TReturnVaue) =
Mock<'TAbstract>((mi, (args, ReturnFunc(f)))::calls)
/// Calls the specified function to compute the return value
[<RequiresExplicitTypeArguments>]
member this.Calls<'TArgs>(f:'TArgs -> 'TReturnValue) =
Mock<'TAbstract>((mi, (args, Call(f)))::calls)
/// Specifies the exception a method raises
[<RequiresExplicitTypeArguments>]
member this.Raises<'TException when 'TException : (new : unit -> 'TException)
and 'TException :> exn>() =
Mock<'TAbstract>((mi, (args, Raise(typeof<'TException>)))::calls)
/// Generic builder for specifying event values
and EventBuilder<'TAbstract,'TEvent when 'TAbstract : not struct>
internal (handlers, calls) =
let add, remove = handlers
/// Specifies the published event value
member this.Publishes(value:'TEvent) =
Mock<'TAbstract>((add, ([|Any|], Handler("AddHandler",value)))::
(remove, ([|Any|], Handler("RemoveHandler",value)))::
calls)
|
1:
2:
3:
4:
5:
6:
7:
8:
9:
|
[<Sealed>]
type It private () =
/// Marks argument as matching any value
[<Wildcard>] static member IsAny<'TArg>() = Unchecked.defaultof<'TArg>
[<AutoOpen;CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module It =
/// Marks argument as matching any value
let [<Wildcard>] inline any () : 'TArg = It.IsAny()
|
1:
2:
3:
4:
5:
|
let mock =
Mock<System.Collections.IList>()
.Setup(fun x -> <@ x.Contains(any()) @>).Returns(true)
.Create()
mock.Contains("Anything")
|
1:
2:
3:
4:
5:
|
let mock =
Mock<System.Collections.IList>()
.Setup(fun x -> <@ x.Count @>).Returns(1)
.Create()
mock.Count = 1
|
1:
2:
3:
4:
5:
6:
7:
|
let counter = ref 0
let mock =
Mock<System.Collections.IList>()
.Setup(fun x -> <@ x.Count @>).Returns(fun () -> incr counter; !counter)
.Create()
mock.Count = 1
mock.Count = 2
|
1:
2:
3:
4:
5:
6:
7:
|
let mock =
Mock<System.Collections.Generic.IList<double>>()
.Setup(fun x -> <@ x.Item( -1 ) @>).Raises<IndexOutOfRangeException>()
.Setup(fun x -> <@ x.Item(any()) @>).Returns(-1.0)
.Create()
mock.[0] = 0.0
mock.[1] = -1.0
|
1:
2:
3:
4:
5:
6:
7:
8:
|
let mutable called = false
let instance =
Mock<System.Collections.Generic.IList<string>>()
.Setup(fun x -> <@ x.Insert(any(), any()) @>)
.Calls<int * string>(fun (index,item) -> called <- true)
.Create()
instance.Insert(6, "Six")
called
|
1:
2:
3:
4:
5:
6:
7:
8:
9:
|
let event = Event<_,_>()
let mock =
Mock<System.ComponentModel.INotifyPropertyChanged>()
.SetupEvent(fun x -> <@ x.PropertyChanged @>).Publishes(event.Publish)
.Create()
let triggered = ref false
mock.PropertyChanged.Add(fun x -> triggered := true)
event.Trigger(mock, System.ComponentModel.PropertyChangedEventArgs("PropertyName"))
triggered.Value
|
Multiple items
type Mock<'TAbstract (requires reference type)> =
new : unit -> Mock<'TAbstract>
internal new : calls:(MethodInfo * (Arg [] * Result)) list -> Mock<'TAbstract>
member Create : unit -> 'TAbstract
member Setup : f:('TAbstract -> Expr<'TReturnValue>) -> ResultBuilder<'TAbstract,'TReturnValue>
member SetupEvent : f:('TAbstract -> Expr<'TEvent>) -> EventBuilder<'TAbstract,'TEvent>
Full name: Script.Mock<_>
Generic mock type over abstract types and interfaces
--------------------
new : unit -> Mock<'TAbstract>
Constructs mock builder
internal new : calls:(MethodInfo * (Arg [] * Result)) list -> Mock<'TAbstract>
val not : value:bool -> bool
Full name: Microsoft.FSharp.Core.Operators.not
val calls : (MethodInfo * (Arg [] * Result)) list
val abstractType : Type
Abstract type
val typeof<'T> : Type
Full name: Microsoft.FSharp.Core.Operators.typeof
val toArgs : (seq<#Expr> -> Arg [])
Converts argument expressions to Arg array
val args : seq<#Expr>
val hasAttribute : (Type -> MethodInfo -> bool)
val a : Type
val mi : MethodInfo
type MethodInfo =
inherit MethodBase
member Equals : obj:obj -> bool
member GetBaseDefinition : unit -> MethodInfo
member GetGenericArguments : unit -> Type[]
member GetGenericMethodDefinition : unit -> MethodInfo
member GetHashCode : unit -> int
member MakeGenericMethod : [<ParamArray>] typeArguments:Type[] -> MethodInfo
member MemberType : MemberTypes
member ReturnParameter : ParameterInfo
member ReturnType : Type
member ReturnTypeCustomAttributes : ICustomAttributeProvider
Full name: System.Reflection.MethodInfo
MemberInfo.GetCustomAttributes(inherit: bool) : obj []
MemberInfo.GetCustomAttributes(attributeType: Type, inherit: bool) : obj []
val arg : #Expr
Multiple items
active recognizer Value: Expr -> (obj * Type) option
Full name: Microsoft.FSharp.Quotations.Patterns.( |Value|_| )
--------------------
type internal Value = obj
Full name: Script.CodeEmit.Value
Boxed value
val v : obj
val t : Type
active recognizer Coerce: Expr -> (Expr * Type) option
Full name: Microsoft.FSharp.Quotations.Patterns.( |Coerce|_| )
Multiple items
union case Arg.Arg: Value -> Arg
--------------------
type internal Arg =
| Any
| Arg of Value
Full name: Script.CodeEmit.Arg
Method argument type
active recognizer PropertyGet: Expr -> (Expr option * PropertyInfo * Expr list) option
Full name: Microsoft.FSharp.Quotations.Patterns.( |PropertyGet|_| )
union case Option.None: Option<'T>
val pi : PropertyInfo
PropertyInfo.GetValue(obj: obj, index: obj []) : obj
PropertyInfo.GetValue(obj: obj, invokeAttr: BindingFlags, binder: Binder, index: obj [], culture: Globalization.CultureInfo) : obj
Multiple items
union case Result.Call: Func -> Result
--------------------
active recognizer Call: Expr -> (Expr option * MethodInfo * Expr list) option
Full name: Microsoft.FSharp.Quotations.Patterns.( |Call|_| )
Multiple items
type WildcardAttribute =
inherit Attribute
new : unit -> WildcardAttribute
Full name: Script.WildcardAttribute
Wildcard attribute
--------------------
new : unit -> WildcardAttribute
union case Arg.Any: Arg
val raise : exn:Exception -> 'T
Full name: Microsoft.FSharp.Core.Operators.raise
Multiple items
type NotSupportedException =
inherit SystemException
new : unit -> NotSupportedException + 2 overloads
Full name: System.NotSupportedException
--------------------
NotSupportedException() : unit
NotSupportedException(message: string) : unit
NotSupportedException(message: string, innerException: exn) : unit
Object.ToString() : string
member Expr.ToString : full:bool -> string
val toCall : (Expr -> MethodInfo * Arg [])
Converts expression to a tuple of MethodInfo and Arg array
union case Option.Some: Value: 'T -> Option<'T>
val x : Expr
val args : Expr list
property Expr.Type: Type
PropertyInfo.GetGetMethod() : MethodInfo
PropertyInfo.GetGetMethod(nonPublic: bool) : MethodInfo
active recognizer PropertySet: Expr -> (Expr option * PropertyInfo * Expr list * Expr) option
Full name: Microsoft.FSharp.Quotations.Patterns.( |PropertySet|_| )
val value : Expr
PropertyInfo.GetSetMethod() : MethodInfo
PropertyInfo.GetSetMethod(nonPublic: bool) : MethodInfo
val expr : Expr
val toHandlers : (Expr -> MethodInfo * MethodInfo)
Converts expression to corresponding event Add and Remove handlers
active recognizer Lambda: Expr -> (Var * Expr) option
Full name: Microsoft.FSharp.Quotations.Patterns.( |Lambda|_| )
val addHandler : MethodInfo
val removeHandler : MethodInfo
val this : Mock<'TAbstract> (requires reference type)
member Mock.Setup : f:('TAbstract -> Expr<'TReturnValue>) -> ResultBuilder<'TAbstract,'TReturnValue>
Full name: Script.Mock`1.Setup
Specifies a method or property of the abstract type as a quotation
val f : ('TAbstract -> Expr<'TReturnValue>) (requires reference type)
Multiple items
type Expr =
override Equals : obj:obj -> bool
member GetFreeVars : unit -> seq<Var>
member Substitute : substitution:(Var -> Expr option) -> Expr
member ToString : full:bool -> string
member CustomAttributes : Expr list
member Type : Type
static member AddressOf : target:Expr -> Expr
static member AddressSet : target:Expr * value:Expr -> Expr
static member Application : functionExpr:Expr * argument:Expr -> Expr
static member Applications : functionExpr:Expr * arguments:Expr list list -> Expr
...
Full name: Microsoft.FSharp.Quotations.Expr
--------------------
type Expr<'T> =
inherit Expr
member Raw : Expr
Full name: Microsoft.FSharp.Quotations.Expr<_>
val default' : 'TAbstract (requires reference type)
module Unchecked
from Microsoft.FSharp.Core.Operators
val defaultof<'T> : 'T
Full name: Microsoft.FSharp.Core.Operators.Unchecked.defaultof
val call : MethodInfo * Arg []
Multiple items
type ResultBuilder<'TAbstract,'TReturnValue (requires reference type)> =
internal new : call:(MethodInfo * Arg []) * calls:(MethodInfo * (Arg [] * Result)) list -> ResultBuilder<'TAbstract,'TReturnValue>
member Calls : f:('TArgs -> 'TReturnValue) -> Mock<'TAbstract>
member Raises : unit -> Mock<'TAbstract>
member Returns : value:'TReturnValue -> Mock<'TAbstract>
member Returns : f:(unit -> 'TReturnVaue) -> Mock<'TAbstract>
Full name: Script.ResultBuilder<_,_>
Generic builder for specifying method or property results
--------------------
internal new : call:(MethodInfo * Arg []) * calls:(MethodInfo * (Arg [] * Result)) list -> ResultBuilder<'TAbstract,'TReturnValue>
member Mock.SetupEvent : f:('TAbstract -> Expr<'TEvent>) -> EventBuilder<'TAbstract,'TEvent>
Full name: Script.Mock`1.SetupEvent
Specifies an event of the abstract type as a quotation
val f : ('TAbstract -> Expr<'TEvent>) (requires reference type)
val handlers : MethodInfo * MethodInfo
Multiple items
type EventBuilder<'TAbstract,'TEvent (requires reference type)> =
internal new : handlers:(MethodInfo * MethodInfo) * calls:(MethodInfo * (Arg [] * Result)) list -> EventBuilder<'TAbstract,'TEvent>
member Publishes : value:'TEvent -> Mock<'TAbstract>
Full name: Script.EventBuilder<_,_>
Generic builder for specifying event values
--------------------
internal new : handlers:(MethodInfo * MethodInfo) * calls:(MethodInfo * (Arg [] * Result)) list -> EventBuilder<'TAbstract,'TEvent>
member Mock.Create : unit -> 'TAbstract
Full name: Script.Mock`1.Create
Creates an instance of the abstract type
val internal mock : calls:(MethodInfo * (Arg [] * Result)) list -> 'TAbstract (requires reference type)
Full name: Script.CodeEmit.mock
Builds a mock from the specified calls
val args : Arg []
val this : ResultBuilder<'TAbstract,'TReturnValue> (requires reference type)
member ResultBuilder.Returns : value:'TReturnValue -> Mock<'TAbstract>
Full name: Script.ResultBuilder`2.Returns
Specifies the return value of a method or property
val value : 'TReturnValue
val result : Result
type unit = Unit
Full name: Microsoft.FSharp.Core.unit
union case Result.Unit: Result
union case Result.ReturnValue: Value -> Result
member ResultBuilder.Returns : f:(unit -> 'TReturnVaue) -> Mock<'TAbstract>
Full name: Script.ResultBuilder`2.Returns
Specifies a computed return value of a method or property
val f : (unit -> 'TReturnVaue)
union case Result.ReturnFunc: Func -> Result
Multiple items
type RequiresExplicitTypeArgumentsAttribute =
inherit Attribute
new : unit -> RequiresExplicitTypeArgumentsAttribute
Full name: Microsoft.FSharp.Core.RequiresExplicitTypeArgumentsAttribute
--------------------
new : unit -> RequiresExplicitTypeArgumentsAttribute
member ResultBuilder.Calls : f:('TArgs -> 'TReturnValue) -> Mock<'TAbstract>
Full name: Script.ResultBuilder`2.Calls
Calls the specified function to compute the return value
val f : ('TArgs -> 'TReturnValue)
member ResultBuilder.Raises : unit -> Mock<'TAbstract>
Full name: Script.ResultBuilder`2.Raises
type exn = Exception
Full name: Microsoft.FSharp.Core.exn
union case Result.Raise: Type -> Result
val add : MethodInfo
val remove : MethodInfo
val this : EventBuilder<'TAbstract,'TEvent> (requires reference type)
member EventBuilder.Publishes : value:'TEvent -> Mock<'TAbstract>
Full name: Script.EventBuilder`2.Publishes
Specifies the published event value
val value : 'TEvent
Multiple items
union case Result.Handler: string * PublishedEvent -> Result
--------------------
type Handler<'T> =
delegate of obj * 'T -> unit
Full name: Microsoft.FSharp.Control.Handler<_>
Multiple items
type SealedAttribute =
inherit Attribute
new : unit -> SealedAttribute
new : value:bool -> SealedAttribute
member Value : bool
Full name: Microsoft.FSharp.Core.SealedAttribute
--------------------
new : unit -> SealedAttribute
new : value:bool -> SealedAttribute
Multiple items
type It =
private new : unit -> It
static member IsAny : unit -> 'TArg
Full name: Script.It
--------------------
private new : unit -> It
static member It.IsAny : unit -> 'TArg
Full name: Script.It.IsAny
Marks argument as matching any value
Multiple items
type AutoOpenAttribute =
inherit Attribute
new : unit -> AutoOpenAttribute
new : path:string -> AutoOpenAttribute
member Path : string
Full name: Microsoft.FSharp.Core.AutoOpenAttribute
--------------------
new : unit -> AutoOpenAttribute
new : path:string -> AutoOpenAttribute
Multiple items
type CompilationRepresentationAttribute =
inherit Attribute
new : flags:CompilationRepresentationFlags -> CompilationRepresentationAttribute
member Flags : CompilationRepresentationFlags
Full name: Microsoft.FSharp.Core.CompilationRepresentationAttribute
--------------------
new : flags:CompilationRepresentationFlags -> CompilationRepresentationAttribute
type CompilationRepresentationFlags =
| None = 0
| Static = 1
| Instance = 2
| ModuleSuffix = 4
| UseNullAsTrueValue = 8
| Event = 16
Full name: Microsoft.FSharp.Core.CompilationRepresentationFlags
CompilationRepresentationFlags.ModuleSuffix: CompilationRepresentationFlags = 4
val any : unit -> 'TArg
Full name: Script.ItModule.any
Marks argument as matching any value
type It =
private new : unit -> It
static member IsAny : unit -> 'TArg
Full name: Script.It
static member It.IsAny : unit -> 'TArg
Marks argument as matching any value
val mock : Collections.IList
Full name: Script.Method Example.mock
namespace System
namespace System.Collections
type IList =
member Add : value:obj -> int
member Clear : unit -> unit
member Contains : value:obj -> bool
member IndexOf : value:obj -> int
member Insert : index:int * value:obj -> unit
member IsFixedSize : bool
member IsReadOnly : bool
member Item : int -> obj with get, set
member Remove : value:obj -> unit
member RemoveAt : index:int -> unit
Full name: System.Collections.IList
val x : Collections.IList
Collections.IList.Contains(value: obj) : bool
val mock : Collections.IList
Full name: Script.Property Example.mock
property Collections.ICollection.Count: int
val counter : int ref
Full name: Script.Computed Property Example.counter
Multiple items
val ref : value:'T -> 'T ref
Full name: Microsoft.FSharp.Core.Operators.ref
--------------------
type 'T ref = Ref<'T>
Full name: Microsoft.FSharp.Core.ref<_>
val mock : Collections.IList
Full name: Script.Computed Property Example.mock
val incr : cell:int ref -> unit
Full name: Microsoft.FSharp.Core.Operators.incr
val mock : Collections.Generic.IList<double>
Full name: Script.Item Get Example.mock
namespace System.Collections.Generic
type IList<'T> =
member IndexOf : item:'T -> int
member Insert : index:int * item:'T -> unit
member Item : int -> 'T with get, set
member RemoveAt : index:int -> unit
Full name: System.Collections.Generic.IList<_>
Multiple items
val double : value:'T -> float (requires member op_Explicit)
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.double
--------------------
type double = Double
Full name: Microsoft.FSharp.Core.double
val x : Collections.Generic.IList<double>
property Collections.Generic.IList.Item: int -> double
Multiple items
type IndexOutOfRangeException =
inherit SystemException
new : unit -> IndexOutOfRangeException + 2 overloads
Full name: System.IndexOutOfRangeException
--------------------
IndexOutOfRangeException() : unit
IndexOutOfRangeException(message: string) : unit
IndexOutOfRangeException(message: string, innerException: exn) : unit
val mutable called : bool
Full name: Script.Called Example.called
val instance : Collections.Generic.IList<string>
Full name: Script.Called Example.instance
Multiple items
val string : value:'T -> string
Full name: Microsoft.FSharp.Core.Operators.string
--------------------
type string = String
Full name: Microsoft.FSharp.Core.string
val x : Collections.Generic.IList<string>
Collections.Generic.IList.Insert(index: int, item: string) : unit
Multiple items
val int : value:'T -> int (requires member op_Explicit)
Full name: Microsoft.FSharp.Core.Operators.int
--------------------
type int = int32
Full name: Microsoft.FSharp.Core.int
--------------------
type int<'Measure> = int
Full name: Microsoft.FSharp.Core.int<_>
val index : int
val item : string
val event : Event<ComponentModel.PropertyChangedEventHandler,ComponentModel.PropertyChangedEventArgs>
Full name: Script.Event Example.event
Multiple items
module Event
from Microsoft.FSharp.Control
--------------------
type Event<'T> =
new : unit -> Event<'T>
member Trigger : arg:'T -> unit
member Publish : IEvent<'T>
Full name: Microsoft.FSharp.Control.Event<_>
--------------------
type Event<'Delegate,'Args (requires delegate and 'Delegate :> Delegate)> =
new : unit -> Event<'Delegate,'Args>
member Trigger : sender:obj * args:'Args -> unit
member Publish : IEvent<'Delegate,'Args>
Full name: Microsoft.FSharp.Control.Event<_,_>
--------------------
new : unit -> Event<'T>
--------------------
new : unit -> Event<'Delegate,'Args>
val mock : ComponentModel.INotifyPropertyChanged
Full name: Script.Event Example.mock
namespace System.ComponentModel
type INotifyPropertyChanged =
event PropertyChanged : PropertyChangedEventHandler
Full name: System.ComponentModel.INotifyPropertyChanged
val x : ComponentModel.INotifyPropertyChanged
event ComponentModel.INotifyPropertyChanged.PropertyChanged: IEvent<ComponentModel.PropertyChangedEventHandler,ComponentModel.PropertyChangedEventArgs>
property Event.Publish: IEvent<ComponentModel.PropertyChangedEventHandler,ComponentModel.PropertyChangedEventArgs>
val triggered : bool ref
Full name: Script.Event Example.triggered
member IObservable.Add : callback:('T -> unit) -> unit
val x : ComponentModel.PropertyChangedEventArgs
member Event.Trigger : sender:obj * args:'Args -> unit
Multiple items
type PropertyChangedEventArgs =
inherit EventArgs
new : propertyName:string -> PropertyChangedEventArgs
member PropertyName : string
Full name: System.ComponentModel.PropertyChangedEventArgs
--------------------
ComponentModel.PropertyChangedEventArgs(propertyName: string) : unit
property Ref.Value: bool
More information