Share this page
Share this page E-mail this page Print this page RSS feeds
Home > Projects > Stubs > Stubs - Getting Started with Stubs
Stubs - Getting Started with Stubs

What is Stubs?

Stubs is a framework for test stubs solely based on delegates. The Stubs framework is now part of the Moles framework.

Basic use of Stubs

Stubs are always located in a subnamed namespace '.Moles' and their names is created by prepending 'S' to the type name. Stubs implement explicitely the interface members, thus simply cast them to the stubbed interface to start using them in the test.

// create stub and attach behavior
var stub = new SIFoo(); // stuf of IFoo
stub.Bla = () => Console.WriteLine("hello");
 
// cast the stub to the interface under test
IFoo foo = stub;
foo.Bla(); // this will call our lambda

Methods

// method with parameters use a delegate with the same signature
stub.Add = (a, b) => a + b;
// one last out parameters is supported
stub.TryParse = delegate(string value, out int result) {
return int.TryParse(value, out result);
};

Properties

// getters and setters have their own delegates
stub.NameGet = () => "bill";
stub.NameSet = (value) => ; // do nothing

Recursive Properties

// Stubs provides helper method to enable recursive stubs
// ChildGetAsStub instantiate SIChild as needed
// and stores it in the stub.
stub.ChildGetAsStub<SIChild>().NameGet = () => "joe";

Events

// event backing fields are exposed publicly
// simply invoke it!
stub.NameChanged();

Partial Stubs

 // call base instead of the fallback behavior
var stub = new SFooBase() { CallBase = true };

Stubs with state

// locals can be used to hold state. C# will emit the closure for you.
string name = null; 
// the C# compiler will create a closure to hold name
stub.NameGet = () => name;
stub.NameSet = (value) => name = value;

Generating Stubs

The code generation of Stubs is configured through .moles files (see [Add New Item/Moles and Stubs for Testing]).

<Moles xmlns="http://schemas.microsoft.com/moles/2010/">
  <Assembly Name="FooBar" />
</Moles>

.moles files must be located on the root any C# project and the Moles and Stubs code generator will automatically emit the files.