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.
MockIXXX.Key.Returns(999);

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
MockObject.Received(1).UpdateView();
// 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 ) );  

Checking calls were received in a particular order:
Received.InOrder(() =>
{
 MockIXxx.SomeMethodCall();
 MockIYyy.AnotherMethodCall(Arg.Any<string>());
});