-
Notifications
You must be signed in to change notification settings - Fork 1
Use with mocking
Overview | How To | Use With Mocking
he following simplistic example shows how the library might be used with the Moq
framework to return an auto-generated instance pre-populated with test values. The test takes advantage of the fact that the Username/Password members of the generated instance are predicable, and therefore is able to validate the application logic within the UserService Login method.
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 is the same test now implemented using the AutoObjectBuilder library which reduces the number of Mocking set-up. Obviously the efficiencies gained by using the framework increase with more complex examples as there is no longer any requirement to define expectations on the mocked return value.
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"));