Csharp example of using Rhino AutoMocker Structuremap

Jan 13, 2013 00:00 · 264 words · 2 minute read Programming Structuremap Test

What is AtuoMocker?

Structuremap Automocker is an IOC container that help us to construct classes with all of its dependencies.you can download Structuremap via Nuget . [more info]

When using it ?

Sometimes your class has too many dependencies and you don’t want to worry about them. Also it is useful when your classes’s constructor change frequently and you don’t want to break your tests.


In the code below we have Machine class which have two dependencies i.e. “IDeviceManager”, “Iproduct”.

public class Machine {
	private IDeviceManager _deviceManager;
	private Iproduct _product;
	public Machine(IDeviceManager deviceManager,Iproduct product) {
	    _deviceManager = deviceManager;
	    _product = product;

	public void RegisterNewDevice(Device device) {
		_deviceManager.AddedSucessfully = true;
		if (!_product.IsOutOfStock(device)) {
		_deviceManager.special = _deviceManager.IsSpecialProduct(device) ? "Special" : "Not Special";


In the test section, we try to assert that if “AddedSucessfully” set to true or not . In this case we can use RhinoAutoMocker to Mock the concrete Machine Class without worrying about its dependencies.

public void Given_device_when_RegisterNewDevice_then_AddedSucessfullyShouldSetToTrue() {
	var autoMocker=new RhinoAutoMocker<Machine>();
	var device=new Device {ID=1,Name = "printer"};
	autoMocker.Get<IDeviceManager>().AssertWasCalled(x => x.AddedSucessfully = true);


In order to test that if the Add method will be called if the IsOutOfStock return false . we have to stubbing the interface of product class like below.

public void Given_device_when_TheStockIsNotOutOfOrder_then_AddMethodShouldCalled() {
	var autoMocker = new RhinoAutoMocker<Machine>();
	var device = new Device { ID = 1, Name = "printer" };
	var product = autoMocker.Get<Iproduct>();
	product.Stub(x => x.IsOutOfStock(Arg<Device>.Is.Anything)).Return(false);
	autoMocker.Get<IDeviceManager>().AssertWasCalled(x => x.Add(device));


Feel free to download the source code of this example from my [ GitHub ].