Saturday, July 18, 2009

AAA with Moq

With the introduction of Moq (The only mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions)), developing unit test cases can be more productive, type-safe and refactoring-friendly. With Moq I don’t have to write my Record/ Playback methods and can be used as a very simple API.

I have re-written my previous sample of AAA pattern using moq as

[TestClass()]

public class When_Getting_All_Products_From_Store : ArrangeAssertActTearDown<ProductService>

{

private Mock<IProductRepository> ___ProductRepository;

private Mock<IStoreRepository> ___StoreRepository;

private Store ___Store;

private IEnumerable<Product> ___Products;

private long __StoreIntId = 3;

public override void Arrange()

{

___ProductRepository = new Mock<IProductRepository>();

___StoreRepository = new Mock<IStoreRepository>();

}

public override ProductService CreateSUT()

{

return new ProductService(___ProductRepository.Object, ___StoreRepository.Object);

}

public override void Act()

{

___Store = new Store();

___Products = new List<Product>();

//Use of lambda expressions and no Record here!!

___StoreRepository.Setup<Store>(x => x.FindBy(__StoreIntId)).Returns(___Store);

___ProductRepository.Setup<IEnumerable<Product>>(x => x.GetAllProductsFor(___Store)).Returns(___Products);

}

[TestMethod]

[ExpectedException(typeof(ArgumentException))]

public void Should_Throw_Argument_Exception_If_StoreId_Is_Greater_Than_100()

{

var __Target = new ProductService();

var __Result = __Target.GetAllProductsForStore(110);

}

[TestMethod]

public void Should_Return_A_List_Of_Records()

{

//No Playback too

var __Result = SystemUnderTest.GetAllProductsForStore(__StoreIntId);

Assert.AreEqual<IEnumerable<Product>>(__Result, ___Products);

}

public override void TearDown()

{

___ProductRepository = null;

___StoreRepository = null;

}

}

I have also removed by BaseRepository class from the code and moved the mocking code to the test class.

No comments: