NUnit not picking up the database connection string

浪子不回头ぞ 提交于 2019-12-24 13:34:12

问题


I have a project(SLR) and an Nunit test project(SLR.Tests)

Every test of a method that interacts with the database fails with an

"object not set to an instance of an object"

exception on the line

using (SqlConnection con = 
new SqlConnection(ConfigurationManager.ConnectionStrings["isvConnectionString"].ToString()))

Hard coding the connection string into the new statement works as expected, and calling the method in course of running the SLR project does not throw any exceptions.

Therefore it appears that NUnit isn't picking up the config file

I've checked that the Bin folder of the SLR. Tests folder contains SLR.DLL and SLR.DLL.Config and that the config file is the same as the web.config file in the SLR project.

The Test project has both NUnit(V3.10.1) and NUit3TestAdapter(V3.10.0) installed.

Any thoughts on what's going on here?


回答1:


The test project needs app.cofig with similar settings present as in the project being tested.

Test projects run in a separate app domain so they need their own config file.

The ConfigurationManager reads the config file of the current app domain being run so copy the desired configuration settings over from the project being tested to allow the tests to be exercised as expected.

This issue also exposes how your code is tightly coupled to implementation concerns in terms of using ConfigurationManager directly, and you should consider abstracting configuration access so that they can be mocked/replaced to allow unit tests to be done in isolation.

public interface IConfiguration {
    string AppSetting[string key] { get; }
    string ConnectionStrings[string name] { get; } 
}


来源:https://stackoverflow.com/questions/49449040/nunit-not-picking-up-the-database-connection-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!