已经发布了几个关于依赖注入的具体问题的问题,例如何时使用它以及它有哪些框架.然而,
什么是依赖注入以及何时/为什么应该或不应该使用它?
language-agnostic design-patterns dependency-injection terminology
我有一个Web服务,我正在尝试进行单元测试.在服务中,它从HttpContext类似物中提取了几个值,因此:
m_password = (string)HttpContext.Current.Session["CustomerId"];
m_userID = (string)HttpContext.Current.Session["CustomerUrl"];
Run Code Online (Sandbox Code Playgroud)
在单元测试中,我使用简单的工作者请求创建上下文,如下所示:
SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
HttpContext context = new HttpContext(request);
HttpContext.Current = context;
Run Code Online (Sandbox Code Playgroud)
但是,每当我尝试设置值时 HttpContext.Current.Session
HttpContext.Current.Session["CustomerId"] = "customer1";
HttpContext.Current.Session["CustomerUrl"] = "customer1Url";
Run Code Online (Sandbox Code Playgroud)
我得到null引用异常,表示HttpContext.Current.Session为null.
有没有办法在单元测试中初始化当前会话?
我的控制器中有以下行:
string lTempPath = Path.Combine(Server.MapPath("~/Temp"), lRandomFileName);
Run Code Online (Sandbox Code Playgroud)
问题是服务器不是虚拟的,只能使用getter访问.
我得到了
"该方法或操作未实施."
我该如何模拟这台服务器?
我创建的测试如下:
[TestCase]
public void PreviewActionShouldGenerateUrlOfPdf()
{
//Arrange
var server = MockRepository.GenerateMock<HttpServerUtilityBase>();
server.Stub(s => s.MapPath("~Temp")).Return("~/Temp");
var httpContext = MockRepository.GenerateMock<HttpContextBase>();
httpContext.Stub(hc => hc.Server).Return(server);
httpContext.Server.Stub(s => s.MapPath("~/Temp")).Return("~/Temp");
var controller = new StudiesController()
{
ReportingService = MockRepository.GenerateMock<IReportingService>(),
SecurityService = MockRepository.GenerateMock<ISecurityService>()
};
controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);
controller.ReportingService.Stub(rs => rs.GetStudyByGID(new Guid())).Return(new Study());
controller.ReportingService.Stub(rs => rs.ListPractices()).Return(new[] { new Practice(), new Practice() });
controller.SecurityService.Stub(ss => ss.GetUser("")).IgnoreArguments().Return(new User());
controller.ControllerContext.HttpContext = MockRepository.GeneratePartialMock<FakeHttpContext>("http://test.com");
controller.HttpContext.User = new FakePrincipal(new FakeIdentity("test"), …Run Code Online (Sandbox Code Playgroud) 我正在使用HttpContext.Current.Server.MapPath()我的方法来获取文档.
要为此方法编写单元测试,
我该怎么做:
我怎么嘲笑这个?
我经历做一个单元测试只对Current.Server.Mappath()不Path.Combine()
unit-testing ×3
mocking ×2
asp.net ×1
asp.net-mvc ×1
c# ×1
httpcontext ×1
terminology ×1
web-services ×1