【发布时间】:2015-06-30 06:30:26
【问题描述】:
我正在尝试对这个使用应用程序变量的应用程序进行单元测试。程序中没有接口或虚拟方法,我发现很难让 Moq 工作。
使用应用程序变量的类:
static string Username = HttpContext.Current.Application["Username"].ToString();
在global.asax文件中初始化。
我的单元测试:
[TestMethod]
public void TestGetCompanyList()
{
Mock<HttpContextBase> context = new Mock<HttpContextBase>();
Mock<HttpApplication> app = new Mock<HttpApplication>();
context.Setup(ctx => ctx.ApplicationInstance).Returns(app); //ERROR
var accountController = new AccountServiceController();
accountController.ControllerContext = new ControllerContext(context.Object, new RouteData(), accountController); //ERROR
CompInput cInput = new CompInput();
cInput.IssuerName = "Addams";
cInput.Ticker = "AD";
var result = accountController.CompList(cInput) as IEnumerable<CompListResult>;
Assert.IsNotNull(result);
}
第一个错误:
Error 4 The best overloaded method match for Moq.Language.IReturns<System.Web.HttpContextBase,System.Web.HttpApplication>.Returns(System.Web.HttpApplication)' has some invalid arguments
Error 5 Argument 1: cannot convert from 'Moq.Mock<System.Web.HttpApplication>' to 'System.Web.HttpApplication'
第二个错误:
Error 6 The best overloaded method match for 'System.Web.Mvc.ControllerContext.ControllerContext(System.Web.HttpContextBase, System.Web.Routing.RouteData, System.Web.Mvc.ControllerBase)' has some invalid arguments
Error 7 Argument 3: cannot convert from 'Stocktrage.Investor.AccountServiceAPI.Controllers.AccountServiceController' to 'System.Web.Mvc.ControllerBase'
这是我第一次使用 Moq(或任何模拟工具),所以我不能 100% 确定这是否可以在没有接口的情况下完成。
【问题讨论】:
-
您不应该尝试模拟您不拥有的对象。你最终会跳过障碍并编写大量代码
-
我拥有这些物品。
HttpContext.Current.Application["Username"]是我在全局 asax 文件中声明的。 -
你不拥有 HttpContext,只是你放在那里的一个变量。无论如何,你的问题在这里:
context.Setup(ctx => ctx.ApplicationInstance).Returns(app);应该是:context.Setup(ctx => ctx.ApplicationInstance).Returns(app.Object); -
这可能对你有一些帮助:stackoverflow.com/questions/1452418/…
标签: c# asp.net-mvc unit-testing mocking moq