测试CreateAccount方法时遇连接字符串缺失的System.InvalidOperationException错误
解决xUnit测试中Entity Framework连接字符串找不到的问题
问题详情
我需要测试一个创建账户的CreateAccount方法,方法代码如下:
public users CreateAccount(string _username, double _weight, string _password) { using (var db = new db_modelContainer()) { Daily_summary summary = new Daily_summary { weight = _weight}; Users_dishes_gallery user_dishes = new Users_dishes_gallery { }; var x = db.usersSet; foreach (var i in x) { if (_username == i.name) { throw new CreateAccountFailException("Username is already occupied!"); } } users newuser = new users { name = _username, weight = _weight, password = _password}; db.usersSet.Add(newuser); db.SaveChanges(); return newuser; } }
我在独立的xUnit测试项目中编写了测试用例:
[Fact] //[AutoRollback] public void CreateAccount_GivenNotOccupiedUsername_CreateSucceed() { string expectedLogin = "test"; string expectedPassword = "test"; double expectedWeight = 30; Users user = new Users(); users createduser = user.CreateAccount(expectedLogin, expectedWeight,expectedPassword); // 断言 Assert.Equal(expectedLogin, createduser.name); Assert.Equal(expectedPassword, createduser.password); Assert.Equal(expectedWeight, createduser.weight); }
运行测试时抛出错误:
System.InvalidOperationException : 找不到名为'db_modelContainer'的连接字符串。
我已尝试将包含EDMX的主项目设为启动项目,还将主项目的App.config以链接方式添加到测试项目,但问题仍未解决。主项目的App.config配置如下:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <!-- Entity Framework配置相关说明 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <connectionStrings> <add name="db_modelContainer" connectionString="metadata=res://*/Database.db_model.csdl|res://*/Database.db_model.ssdl|res://*/Database.db_model.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SQLEXPRESS;initial catalog=Dietaverse_database;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration>
可行解决方法
1. 直接复制主项目App.config到测试项目
链接文件可能因输出目录规则无法被测试框架读取,直接将主项目的App.config复制到测试项目根目录,确保文件名保持为App.config(测试项目编译后会生成[测试项目名].dll.config,测试框架会读取该文件)。
2. 给DbContext添加带连接字符串参数的构造函数
修改db_modelContainer类,添加支持传入连接字符串的构造函数,这样测试代码可以直接指定连接字符串,无需依赖配置文件:
public db_modelContainer(string connectionString) : base(connectionString) { }
之后可以在测试用例中显式传入连接字符串,或者调整CreateAccount方法支持传入DbContext实例,提升测试灵活性。
3. 确保测试项目配置文件包含完整EF配置
测试项目的App.config必须包含主项目配置中的configSections和entityFramework节点,Entity Framework依赖这些配置才能完成初始化,仅复制连接字符串不足以解决问题。
4. 对齐测试项目与主项目的目标框架
主项目使用.NET Framework 4.7.2,测试项目必须设置为相同的目标框架,否则配置文件的读取逻辑会出现差异,导致连接字符串无法被识别。
内容的提问来源于stack exchange,提问作者Stray
相关产品推荐
相关产品推荐

