I’m building a class library in C# for two projects. This class library does a lot of connections to an SQLServer database.
As this library only retrieves data from the SQLServer database so there is an static class that is in charge of load the connection settings and open it. Then the classes of the library receive the required data to do the query and returns the result. All this is done using static methods.
Something like this.
internal static class DBConnection
{
private const String connectionString = "some connection string";
public static SqlConnection open() { /* ... open the connection ... */ }
}
public static class DataXRetriever
{
public static List<DataX> RetrieveById(Int32[] ids)
{
using (SqlConnection connection = DBConnection.open())
{
/* ... do a query ... */
/* ... do something with the result of the query ... */
/* ... return it ... */
}
}
/* ... some other static methods ... */
}
I want to make a test unit for these kind of methods without the need to be connecting to the database, I’ve been reading that this can be done instantiating the class that contains the connection and give it to the class that will use it, but my design doesn’t work like that.
You could allow code to modify your connection string instead of making it static, and then have your unit test setup code change its value before running the tests. (Update: On second thought, for the specific thing you’re trying to do, even that wouldn’t really work.)
But the right way to do this is to program against interfaces that get injected into your class, so that they can be easily mocked on a case-by-case basis.
In other words, if your design “doesn’t work like that,” then your design is wrong, and it needs to be changed.