October 12, 2016

Using NSubstitute

A good quick guide is provided - Quick Guide

Create a mock for a given inteface:
MockIXXX = Substitute.For<Ixxx>();
The mocked methods always do nothing and return the default value.

Afterwards can mock a return value:
MockIXXX.GetDuplicates().Returns( GetSomeTestResults() ); 
where GetSomeTestResults() is a test method returning the desired results.

A property can be Mocked using standard notation (if it has a getter and a setter)
MockIXXX.Name = "Algol";
When the property is a getter only use the following technique.

Do something when a method AddSelection(ISelection) is called with any parameters:
MockIXXX.When( x => x.AddSelection( Arg.Any<ISelection>() ) ).
    Do( arg => dummySelections.Add( arg.Arg<ISelection>() ) );
here dummySelections is a list local to the test.

When testing results: 
// Test 1 call to UpdateView was received on the given MockObject
// Test a property was set to a particular value
MockObject.Received().SomeProperty = 10.0d;
// Test no calls to RemovePage were received on the given MockObject with the specified arguments  
MockObject.DidNotReceive().RemovePage( Arg.Any<IControl>() ); 

// Test 1 call to Add() was received on the given MockObject with the given argument
MockObject.Received(1).Add( Arg.Is<INotification>( arg => arg.Id == NotificationEnum.Clean ) ); 
// No calls to Add() were received on the given MockObject with the given argument
MockObject.DidNotReceive().Add( Arg.Is<INotification>( arg => arg.Id == NotificationEnum.Clean ) )
// Test a call was received regardless of the argument value
MockObject.Received( 1 ).Calculate( Arg.Any() );

// When you have multiple tests in a test fixture you sometimes need to clear the received calls
// otherwise the previous tests could have increased the call count

Checking calls were received in a particular order:
Received.InOrder(() =>

NSubstitute syntax for raising events is a bit more subtle:
MockObject.SomeEvent += Raise.EventWith(new object(), new EventArgs());
See the NSubstitute documentation here