Final mocking is one of the advanced features supported in Telerik JustMock.
It allows you to fake final method/property calls, set expectations and verify results using the AAA principle.
Faking final or virtual method/property calls doesn't affect the way you write your tests, i.e. the same syntax is used
for mocking both final and non-final calls.
This feature is available only in the commercial version of Telerik JustMock.
Refer to this topic to learn more about the differences between both the commercial and free versions of Telerik JustMock.
In the further examples we will use the following sample classes to test:
Assert Final Method Setup
Set up a call to a final method and assert its return value.
Here we setup that a call to the final foo.Echo method with any int argument
should return 10.
Follows the same example in F#:
member this.ShouldMockFinalMember() =
let foo = Mock.Create<Foo>()
Mock.Arrange(foo, fun foo -> foo.Echo(Arg.AnyInt)).Returns(10);
let ret = foo.Echo(1)
Assert Property Get
Set up a call to a final property and assert its return value.
Here we setup that a call to the final foo.FooProp property should return the "bar" literal.
Assert Property Set
In this example we arrange the FooProp property of the Foo class.
Here we setup that setting the final foo.FooProp property to any string value
different from "ping" will cause an exception of type MockException to be thrown.
Assert Method Overloads
This example shows how to mock final method overloads.
foo.Execute has two overloads - accepting one or two integers as arguments.
Here we mock them both by Returns. In the first case we return just the argument that has been passed.
In the second case we return the sum of the two integer values.
After that, we act by calling both overloads and assert what we have arranged.
Assert Method Callbacks
Follows an example of how to use the Raises method to fire a callback
and pass event arguments once a final method is called.
When the foo.Echo() method is called with any integer value as argument
the OnEchoCallback is raised with parameter true. We attach a delegate to
the event to set a local boolean variable to true once the method is called.
We act by calling foo.Echo(10).
Finally, we verify that foo.Echo() has been called in our test.
Assert Generic Types and Methods
You can also assert generic types and methods. In the example below we mock generic method
in non-generic type. We arrange that it should return the string value that has been passed to it.
For more information about mocking generic types and methods go to Generics topic.