我正在学习在VS2010中构建单元测试功能的微软,并遇到了一个问题。
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void SomeTest()
{
//Arrange
HomeController controller = new HomeController();
//Act
ViewResult results = controller.Index() as ViewResult;
//Assert
ViewDataDictionary viewData = results.ViewData;
Assert.AreEqual(null, viewData["Message"]);
}
}
我知道这会失败,这不是问题。然而,问题是我正在点击我的EntityFramework模型“myModel.edmx”并收到错误"System.ArgumentException: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid."
这是在MyModel.Designer.cs文件中。有问题的一行是:
public Tool_Entities() : base("name=Tool_Entities", "Tool_Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
我知道这行是正常的,因为当我运行非测试项目时,我可以很好地连接到这个模型。
答案 0 :(得分:3)
您应该以面向服务或存储库的方式从控制器中抽象出EF。这样你就可以为你的单元测试删除依赖(并注入一个模拟),然后测试你的控制器。
首先创建一个界面。这只是一个蓝图,你可以按照你想要的方式制作它。
public interface IToolRepository
{
void Add(Tool something);
IQueryable<Tool> Query { get; }
void Delete(Tool something);
}
然后用EF实现。