I have a asp.net project with a DAL (most code is from someone else but I’m doing maintenance and clean up).
My web application project has a dataprovider class like so:
public class DataProvider : IDataProvider
{
private string DefaultConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["myConnection"]].ConnectionString;
}
}
public T ExecuteMyQuery<T>(parameters)
{
//executes query on db
}
This web application project as has a data layer that interacts between the web pages and the provider like so:
public class MyData : IMyData
{
private readonly IDataProvider dataProvider;
public MyData(IDataProvider dataProvider)
{
this.dataProvider = dataProvider;
}
public string GetTitle(string myVar)
{
//builds up stuff to send
return this.dataProvider.ExecuteMyQuery(...);
}
}
The connection string for this project is in web.config.
Now I have my tests. For simplicity and time constraints I’m using just a test database and will create the actual objects and test against the test database (in theory we would use more mocks, stubs and all sorts of stuff but no time.)
So I have a test project which references my web application project above.
public class MyTests
{
private MyData myData;
private DataProvider dataProvider;
[SetUp]
protected void SetUp()
{
dataProvider = new DataProvider();
mysData = new MyData(dataProvider);
}
[Test]
public void CheckTitles()
{
string title = myData.GetTitle("AVariable");
Assert.AreEqual(title, "A typical title");
}
But this keeps give me a null pointer execption when I run it in NUnit. How do I get my provider to use a new connection string to point to my test database? I tried added an app.config file but it’s not working.
It seems like your app.config (which is copy of web.config) is not loaded as configuration file by default when tests are being run.
I’d prefere to solve that in the following way:
Create
IConfigurationinterface which encapsulates details of getting connectionStringCreate implementation of
IConfigurationwhich readsweb.configto use it in real code)Introduce
IConfigurationdependency intoDataProviderclassSimple refactoring extracts knowledge about reading
web.configfrom yourDataProvider🙂In your test use
IConfigurationstub which returns any connection string what you need for testing. (you can create stub by using mocking framework like moq/rhino-mock or by implementation ofIConfigurationwhich does not read app.config)If reading
web.configis not goal of your tests then that approach is what you need.As a bonus knowledge about configuration reading goes to separated class 🙂