Strict
By default Telerik® JustMock uses loose mocks (Behavior.RecursiveLoose) and allows you to call any method on a given type. No matter whether the method call is arranged or not, you are able to call it. However, you may have a case where you want to enable only arranged calls and to reject non-arranged calls. In such cases you need to set the Behavior to Strict when creating the mock. Another case where you may need to use strict mocks is when arranging calls to property setters.
Caution
If you try to call a method that is not arranged on a strict mock an exception will be thrown -
StrictMockException.
Syntax
Mock.Create<T>(Behavior.Strict);
Examples
Arbitrary Calls Generate Exception in Strict Mocks
The next example shows the creation of a strict mock, without any further arrangements. Calling a non previously arranged member will result in throwing of a MockException.
public interface IFoo
{
void VoidCall();
}[TestMethod]
[ExpectedException(typeof(StrictMockException))]
public void ArbitraryCallsShouldGenerateException()
{
//Arrange
var foo = Mock.Create<IFoo>(Behavior.Strict);
//Act
foo.VoidCall();
}Testing If Functions Work in Isolation
Let assume we have the following class:
public class Foo
{
public void VoidMethod()
{
// Some logic here...
}
public void ExecuteVoidMethod()
{
this.VoidMethod();
}
public string SomeStringFunctiond()
{
return default(string);
}
public int SomeIntFunctiond()
{
return default(int);
}
}Now, we want to test the ExecuteVoidMethod() function. The next test should throw a MockException if non-arranged member is called. In our case such member is the VoidMethod() function:
[TestMethod]
[ExpectedException(typeof(StrictMockException))]
public void ShouldAssertIfThereAreCallsToNonArrangedMembers()
{
// Arrange
var foo = Mock.Create<Foo>(Behavior.Strict);
Mock.Arrange(() => foo.ExecuteVoidMethod()).CallOriginal().OccursAtLeast(1);
// Act
foo.ExecuteVoidMethod();
}The next example shows the basic usage of a strict mock. The test checks for the basic functions of the SUT in isolation:
[TestMethod]
public void ShouldAssertIfThereAreNOArbitraryCalls()
{
// Arrange
var foo = Mock.Create<Foo>(Behavior.Strict);
Mock.Arrange(() => foo.VoidMethod()).OccursAtLeast(1);
Mock.Arrange(() => foo.ExecuteVoidMethod()).CallOriginal().OccursAtLeast(1);
// Act
foo.ExecuteVoidMethod();
// Assert
Mock.Assert(foo);
}First, we create the mock with Behavior.Strict. Then, we arrange the methods that should be invoked during the test execution. Finally, we assert against them.