I have an object (like the HttpContext or other ones) that I would like to mock. Sometimes, there are some unit tests where I'm forced to mock a hefty amount of dependencies, and set their dependencies and values appropriately.
Below there's some sample code to mock the httpcontext and another class:
public static HttpContextBase FakeHttpContext()
{
var context = new Mock<HttpContextBase>();
var files = new Mock<HttpFileCollectionBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
request.Setup(req => req.ApplicationPath).Returns("~/");
request.Setup(req => req.AppRelativeCurrentExecutionFilePath).Returns("~/");
request.Setup(req => req.PathInfo).Returns(string.Empty);
request.Setup(req => req.Form).Returns(new NameValueCollection());
request.Setup(req => req.QueryString).Returns(new NameValueCollection());
request.Setup(req => req.Files).Returns(files.Object);
response.Setup(res => res.ApplyAppPathModifier(MoqIt.IsAny<string>())).
Returns((string virtualPath) => virtualPath);
user.Setup(usr => usr.Identity).Returns(identity.Object);
identity.SetupGet(ident => ident.IsAuthenticated).Returns(true);
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
return context.Object;
}
registrationView = new Mock<IRegistrationView>();
registrationView.SetupGet(v => v.Address).Returns("Calle test");
registrationView.SetupGet(v => v.EmailAddress).Returns("test@test.com");
registrationView.SetupGet(v => v.Password).Returns("testpass");
registrationView.SetupGet(v => v.FirstName).Returns("Name");
registrationView.SetupGet(v => v.LastName).Returns("Surname");
registrationView.SetupGet(v => v.DaytimePhoneNumber).Returns("666666666");
registrationView.SetupGet(v => v.WholeSalers).Returns(new List<UserWholesaler>() {
new UserWholesaler(true) { CollaborationCode = "1234", Region = "TestReg", WholesalerCode = "10", WholesalerName = "TestWS", RegionName = "RegTest" } });
I wonder: is there any library that, with simply a call like "registrationView = new MockWithFilledProperties();", would allow me to create a Mock with properties filled with default values? If so, which one?
Thank you and kind regards.
Best Answer
Moq allows you to stub all properties with
That will make all properties track their values (i.e. you can write some value to property and retrieve it later) and set all properties to their default values.
NOTE: You can use chained mock creation (aka specification queries) to setup mock more quickly