AutoObjectBuilder


Assist Unit Testing with predicatble auto-generated data

Mocking

example

This example shows how the library might be used with the Moq framework. It returns an auto-generated instance pre-populated with test values. Due to the predicable nature of the data, it becomes easy to create asserts with minimal code.

Firstly here’s how we might test our example without the AutoObjectBuilder library.

IPerson personMoq = new Mock<IPerson>();
personMoq.SetUp(o => o.Username).Returns("Username");
personMoq.SetUp(o => o.Password).Returns("Password");

var moq = new Mock<IUserRespository>();
var moq.SetUp(o => o.FindUser(It.IsAny<int>())).Returns(personMoq.Object);

UserService service = new UserService(moq.Object);
var loggedInUser = service.Login("Username", "Password");

Assert.That(loggedInUser, Is.EqualTo(person));
Assert.That(loggedInUser.Username, Is.EqualTo("Username"));
Assert.That(loggedInUser.Password, Is.EqualTo("Password"));

Here’s the same test implemented using AutoObjectBuilder.

 IPerson person = Auto.Make<IPerson>().Object;

 var moq = new Mock<IUserRespository>();
 var moq.SetUp(o => o.FindUser(It.IsAny<int>())).Return(person);

 UserService service = new UserService(moq.Object);
 var loggedInUser = service.Login("Username", "Password");

 Assert.That(loggedInUser, Is.EqualTo(person));
 Assert.That(loggedInUser.Username, Is.EqualTo("Username"));
 Assert.That(loggedInUser.Password, Is.EqualTo("Password"));

This reduces the amount of mocking setup required. Although a simplistic example, you should see how it can produce more readable tests and fewer lines of code.