我有一种使用应用程序变量从外部文件获取信息的方法。由于单元测试中不使用应用程序变量,有没有办法可以从 Global.asax 文件中获取应用程序变量值并能够在测试中使用它们?
这是我的测试方法:
[TestMethod]
public void TestGetCompanyList()
{
var accController = new AccSerController();
CInt cInt = new CInt();
cIn.Iss = "Other";
cIn.Tick = "BK";
var result
= accController.Clist(cIn) as IEnumerable<CList>;
Assert.IsNotNull(result);
}
最佳答案
使用repository pattern 。您的 Controller 不应该对 WebConfiguration
有任何了解。
//This defines the stuff that your controller needs (that your repository should contain)
public interface ISiteConfiguration
{
string Setting1 {get; set;}
}
//Use this in your site. Pull configuration from external file
public class WebConfiguration : ISiteConfiguration
{
public string Setting1 {get; set;}
public WebConfiguration()
{
//Read info from external file here and store in Setting1
Setting1 = File.ReadAllText(HttpContext.Current.Server.MapPath("~/config.txt"));
}
}
//Use this in your unit tests. Manually specify Setting1 as part of "Arrange" step in unit test. You can then use this to test the controller.
public class TestConfiguration : ISiteConfiguration
{
public string Setting1 {get; set;}
}
我正在使用Ninject执行依赖注入(inject),但还有很多其他库。我将在我的答案中省略一些基本的 Ninject 设置,因为有 plenty of resources在那里。但下面的代码显示了如何在 Web 应用程序中指定使用 WebConfiguration
来满足 ISiteConfiguration
的需求。
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ISiteConfiguration>().To<WebConfiguration>();
}
这就是奇迹发生的地方。当在 Web 应用程序中创建 Controller 实例时,Ninject 将查看构造函数并发现它正在请求 ISiteConfiguration
。在您的 Ninject 配置中,您告诉它在需要 ISiteConfiguration
时使用 WebConfiguration
。因此,Ninject 将创建一个新的 WebConfiguration
实例并将其提供(注入(inject))到您的 Controller 。
public class AccountServiceController
{
ISiteConfiguration Config {get; set;}
//This is called constructor injection
public AccountServiceController(ISiteConfiguration config)
{
Config = config;
}
public ActionResult Index()
{
//Now you can use Config without needing to know about ISiteConfiguration's implementation details
//Get settings from Config instead of Application
}
}
您还可以在单元测试中使用 Ninject,但这里有一个更简单的演示,我们没有使用它:
[TestMethod]
public void TestGetCompanyList()
{
//Arrange
var config = new TestConfiguration(){ Setting1 = "mysetting" };
var accountController = new AccountServiceController(config);
}
所有这一切的结果是,您可以轻松地使用 Controller 的操作方法进行单元测试,因为您可以使用您想要的任何 ISiteConfiguration
实现。
关于c# - 如何在 UnitTest asp.net 中使用应用程序变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28814222/