我有一个我想要模拟的对象(比如HttpContext或其他)。有时,有一些单元测试,我被迫嘲笑大量的依赖项,并适当地设置它们的依赖项和值。
下面是一些示例代码,用于模拟httpcontext和另一个类:
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" } });
我想知道:是否有任何库,只需调用&#34; registrationView = new MockWithFilledProperties();&#34;,这将允许我创建一个具有填充默认值的属性的模拟?如果是这样,哪一个?
谢谢你,亲切的问候。
答案 0 :(得分:21)
Moq允许您使用
存根所有属性registrationView.SetupAllProperties();
这将使所有属性跟踪它们的值(即,您可以向属性写入一些值并在以后检索它)并将所有属性设置为其默认值。
注意:您可以使用链式模拟创建(也就是规范查询)来更快地设置模拟
IRegistrationView view = Mock.Of<IRegistrationView>(ctx =>
ctx.Address == "Calle test" &&
ctx.EmailAddress == "test@test.com" &&
ctx.Password == "testpass" &&
ctx.FirstName == "Name" &&
ctx.LastName == "Surname");
答案 1 :(得分:0)
现在你可以这样做:
Mock.Of<IMyclass>()
这会让你传递一个默认对象,如果你真的不需要这个对象,并且它的函数的默认答案是可以的,这会成功。