这是我第一次使用最小起订量,并且无法真正找到有关如何将其用于应用程序变量的好教程。我在我的 Controller 中调用一个调用 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);
}
我不知道如何将应用程序值“连接”到 Controller 。
编辑:
我的 Controller :
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;
}
最佳答案
I in my controller i am calling a method that calls HttpContext.Current.Application["TheConnectionString"]
好的,我们应该从第一条规则开始:
HttpContext.Current == Arch Enemy Of Unit Testing. Search for every single occurrence of this static call in your application and get rid of it.
因此,如果您想有机会模拟和测试它,那么让我们通过将其替换为正确的抽象来删除 Controller 中的这个邪恶调用:
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);
关于c# - 起订量 应用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28841296/