Asp.net mvc 带有单元测试项目的Asp.net Telerik MVC 4应用程序
我创建了一个Asp.net Telerik MVC 4应用程序,其中包含一个单元项目。当我试图在单元测试中初始化用户对象时,它失败了。它给出了一条错误消息,指出配置文件中不存在连接字符串。但是,我检查了配置文件,连接字符串就在那里 以下是一些示例代码: //连接字符串Asp.net mvc 带有单元测试项目的Asp.net Telerik MVC 4应用程序,asp.net-mvc,asp.net-mvc-4,Asp.net Mvc,Asp.net Mvc 4,我创建了一个Asp.net Telerik MVC 4应用程序,其中包含一个单元项目。当我试图在单元测试中初始化用户对象时,它失败了。它给出了一条错误消息,指出配置文件中不存在连接字符串。但是,我检查了配置文件,连接字符串就在那里 以下是一些示例代码: //连接字符串 <connectionStrings> <add name="KMSSEntities" connectionString="metadata=res://*/Models.KMSSEntityMod
<connectionStrings>
<add name="KMSSEntities" connectionString="metadata=res://*/Models.KMSSEntityModel.csdl|res://*/Models.KMSSEntityModel.ssdl|res://*/Models.KMSSEntityModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=KMSS;persist security info=True;user id=******;password=*******;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
//Initialize my Context
private KMSSEntities entity = new KMSSEntities();
//This is my insert user
public void InsertUser(User user)
{
entity.Users.Add(user);
}
//this is code in the test method
User u = new User();
u.UserName = "test";
u.password = "Password";
u.FirstName = "first";
u.LastName = "Last";
StudentRepository rep = new StudentRepository(new KMSSEntities());
rep.InsertUser(u); **//This is where it's returning the error message**
rep.Save();
此配置是否在测试项目的App.config中。还有一个旁注:由于您正在访问配置,所以这不是单元测试。@Raj是的,它在我的App.config文件中。我应该使用模拟对象而不是访问真实的数据库吗?@josianferiice我认为在这种情况下,你应该使用真实的数据库。您正在测试存储库类型的方法,因此集成测试非常适合此目的。调试时,将断点放在连接字符串设置的位置。查看是否可以使用该连接字符串连接到数据库。还要检查是否存在任何不正确的映射。您是否使用相同的代码成功地将real app连接到DB?@Raj,我删除了单元测试项目,并在about controller中对其进行了测试。我能够连接和检索数据,没有问题。因此,这可能是测试项目中的配置问题。
at System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel()
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at KMSS.Models.UserRepository.InsertUser(User user) in c:\com\KMSS\KMSS\KMSS\Models\UserRepository.cs:line 29
at KMSSTests.UnitTest1.TestMethod1() in c:\com\KMSS\KMSS\KMSSTests\UnitTest1.cs:line 21