Rhino Mocks it’s an excelent framework for mocking to use in our unit testings. One reason to use it is that do not make use of strings to hardcoding the names of types, methods, properties, etc, reducing the error posibilities at runtime.
After of 3.0.5 version released some time ago, the sintax became more easier to read and with less probabilities on errors.
At look this introductory screencast you’ll see how to do a typical mocking, and using the standart way to do it. The posibilities to forget the call VerifyCall() method exists.
[Test]
public void SigmoidalFunctionDerivative()
{
INet net = Mock<INet>();
ITransferFunction tf = new SigmoidalTransferFuncion();
Expect
.Call(net.Value)
.Return(5.0);
Mocks.ReplayAll();
//f'(net) = y * ( 1 - y )
Assert.Equal(0.006648057, Math.Round(tf.Derivate(net), 9));
Mocks.VerifyAll();
}
One way to do it more crearly and safety:
[Test]
public void SigmoidalFunctionDerivative()
{
INet net = Mock<INet>();
ITransferFunction tf = new SigmoidalTransferFuncion();
using (Mocks.Record())
{
Expect
.Call(net.Value)
.Return(5.0);
}
using (Mocks.Playback())
{
//f'(net) = y * ( 1 - y )
Assert.Equal(0.006648057, Math.Round(tf.Derivate(net), 9));
}
}
On this examples I’m using a helper for the Mock<T>() method and the MockRepository Mocks {get;set;}. Nothing unusual so far.
[Test]
public void SigmoidalFunctionDerivative()
{
INet net = Mock<INet>();
ITransferFunction tf = new SigmoidalTransferFuncion();
using (Mocks.Record())
{
Expect
.Call(net.Value)
.Return(5.0);
}
using (Mocks.Playback())
{
//f'(net) = y * ( 1 - y )
Assert.Equal(0.006648057, Math.Round(tf.Derivate(net), 9));
}
}
There is another way to do the same but using delegates instead of keyword using: The With class (actually I think that I know where it come from).
[Test]
public void SigmoidalFunctionDerivative()
{
INet net = Mock<INet>();
ITransferFunction tf = new SigmoidalTransferFuncion();
With
.Mocks(Mocks)
.Expecting(delegate
{
Expect
.Call(net.Value)
.Return(5.0);
})
.Verify(delegate
{
//f'(net) = y * ( 1 - y )
Assert.Equal(0.006648057,
Math.Round(tf.Derivate(net), 9));
});
}
I prefer the 2nd option.