如何获取方法单元测试中分配给受保护对象的HttpContext.Current.Server.MapPath的伪路径?

编程入门 行业动态 更新时间:2024-10-23 19:33:48
本文介绍了如何获取方法单元测试中分配给受保护对象的HttpContext.Current.Server.MapPath的伪路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是单元测试的新手,MSTest.我得到NullReferenceException.

I am new to unit test, MSTest. I get NullReferenceException.

如何设置HttpContext.Current.Server.MapPath进行单元测试?

How do I set HttpContext.Current.Server.MapPath for doing unit test?

class Account { protected string accfilepath; public Account(){ accfilepath=HttpContext.Current.Server.MapPath("~/files/"); } } class Test { [TestMethod] public void TestMethod() { Account ac= new Account(); } }

推荐答案

HttpContext.Server.MapPath将需要基础虚拟目录提供程序,该虚拟目录提供程序在单元测试期间不存在.在可以模拟以使代码可测试的服务后面抽象路径映射.

HttpContext.Server.MapPath would require an underlying virtual directory provider which would not exist during the unit test. Abstract the path mapping behind a service that you can mock to make the code testable.

public interface IPathProvider { string MapPath(string path); }

在具体服务的生产实现中,您可以调用以映射路径并检索文件.

In the production implementation of the concrete service you can make your call to map the path and retrieve the file.

public class ServerPathProvider: IPathProvider { public MapPath(string path) { return HttpContext.Current.Server.MapPath(path); } }

您将把抽象注入到您的依赖类中或需要和使用的地方

you would inject the abstraction into your dependent class or where needed and used

class Account { protected string accfilepath; public Account(IPathProvider pathProvider) { accfilepath = pathProvider.MapPath("~/files/"); } }

如果没有可用的模拟框架,请使用您选择的模拟框架或伪造/测试类,

Using your mocking framework of choice or a fake/test class if a mocking framework is not available,

public class FakePathProvider : IPathProvider { public string MapPath(string path) { return Path.Combine(@"C:\testproject\",path.Replace("~/","")); } }

然后您可以测试系统

[TestClass] class Test { [TestMethod] public void TestMethod() { // Arrange IPathProvider fakePathProvider = new FakePathProvider(); Account ac = new Account(fakePathProvider); // Act // ...other test code } }

并且不与HttpContext

更多推荐

如何获取方法单元测试中分配给受保护对象的HttpContext.Current.Server.MapPath的伪路径?

本文发布于:2023-11-09 15:49:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572776.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中分   路径   单元测试   对象   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!