这是我第一次使用moq并且无法找到关于如何将其用于应用程序变量的好教程。我在我的控制器中调用了一个调用HttpContext.Current.Application["TheConnectionString"]
的方法,我调用了我的global.asax并初始化了Application["TheConnectionString"] = "MyConnectionString"
[TestMethod]
public void TestGetCompanyList()
{
string applicationValue = "MyConnectionString";
var mockApplication = new Mock<HttpApplicationStateBase>();
mockApplication.SetupSet(s => s["TheConnectionString"] = It.IsAny<string>()).Callback((string name) => applicationValue = (string)val);
mockApplication.SetupGet(s => s["TheconnectionString"]).Returns(() => applicationValue);
var request = new Mock<HttpRequestBase>();
var context = new Mock<HttpContextBase>();
request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection {{"X-Requested-With", "XMLHttpRequest"}});
context.SetupGet(ctx => ctx.Request).Returns(request.Object);
context.SetupGet(x => x.Application).Returns(applicationValue);
var accController = new AccSerController();
CInt cInt = new CInt();
cIn.Iss = "Other";
cIn.Tick = "BK";
var result = accController.GetClist(cIn) as IEnumerable<CList>;
Assert.IsNotNull(result);
}
我不知道如何将应用程序值“连接”到控制器。
编辑:
我的控制器:
public class AccSerController : ApiController
{
[System.Web.Http.HttpPost]
public dynamic GetCList([FromBody]CompanyInput cInput)
{
AccSerFacade accService = new AccSerFacade();
IEnumerable<CompanyListResult> cList = accService.GetCList(cIn);
return cList;
}
答案 0 :(得分:4)
我在我的控制器中我正在调用一个调用的方法 HttpContext.Current.Application [&#34; TheConnectionString&#34;]
好的,我们应该从第一条规则开始:
HttpContext.Current == Arch Enemy Of Unit Testing。在您的应用程序中搜索此静态调用的每一次出现并删除它。
因此,如果您想要嘲笑和测试它的任何机会,请在控制器中删除此恶意调用,将其替换为适当的抽象:
public ActionResult GetClist(CInt model)
{
string conStr = (string)this.HttpContext.Application["TheConnectionString"];
...
}
现在你可以编写一个合适的单元测试:
// arrange
string applicationValue = "MyConnectionString";
var mockApplication = new Mock<HttpApplicationStateBase>();
mockApplication.SetupGet(s => s["TheConnectionString"]).Returns(applicationValue);
var request = new Mock<HttpRequestBase>();
var context = new Mock<HttpContextBase>();
request.SetupGet(x => x.Headers).Returns(new WebHeaderCollection { { "X-Requested-With", "XMLHttpRequest" } });
context.SetupGet(ctx => ctx.Request).Returns(request.Object);
context.SetupGet(ctx => ctx.Application).Returns(mockApplication.Object);
var sut = new AccSerController();
sut.ControllerContext = new ControllerContext(context.Object, new RouteData(), sut);
CInt cInt = new CInt();
cIn.Iss = "Other";
cIn.Tick = "BK";
// act
var actual = accController.GetClist(cIn);
// assert
Assert.IsNotNull(actual);