问题
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