HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Unit (Integration) Test for code that interacts with a database

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withdatabasethatforintegrationtestcodeinteractsunit

Problem

I am trying to create some (I believe these are Integration not Unit) tests for code that interacts with a database and I am not sure this is the right approach.

I would appreciate any reviews and possible improvements.

Using: VS2010 Unit Testing Framework

This is the function I want to test:

public IDbConnection OpenThirdPartyDatabase(string path, string password)
{
    var provider = GetProvider(path, password);
    return DBObjectFactory.GetObject().GetConnection(provider.Name, true, true);
}


Functions used by OpenThirdPartyDatabase

private static IDBProvider GetProvider(string path, string password)
{
    var providers = DBProviders.GetObject();
    var providerExists = providers.Cast().Any(dbProvider => dbProvider.Name == "MyProviderName");

    return providerExists ? providers.GetDBProvider("MyProviderName") : CreateProvider(path, password); 
}

private static IDBProvider CreateProvider(string path, string password)
{
    IDBProvider provider = new DBAccessProvider("MyProviderName", path, "", password);
    DBProviders.GetObject().Add(provider);

    return provider;
}

public IDbConnection GetConnection(string ProviderName, bool OpenConnection, bool UseConnectionPool)
{
    IDBProvider dbProvider = DBProviders.GetObject().GetDBProvider(ProviderName);
    if (dbProvider == null)
        throw new UndeclaredDBProviderException(ProviderName);
    else
    {
        IDbConnection newConnection = null;
        if ((connectionPool.ContainsConnection(ProviderName)) && (UseConnectionPool))
            newConnection = connectionPool.GetConnection(ProviderName);
        else
        {
            newConnection = dbProvider.GetConnection();
            if (UseConnectionPool)
                connectionPool.AddConnection(ProviderName, newConnection);
        }
        if ((OpenConnection) && (newConnection.State == ConnectionState.Closed))
            newConnection.Open();
        return newConnection;
    }
}


Tests:

```
///
/// Test Connection

Solution

I don't claim to be an expert, but here's my experience.

Apart from that i see you are using a constant string "MyProviderName" in your code and you would do well to move that to a const string for easy refactoring and future changes.

Also i suggest you use the more common "ArgumentNullException" vs creating your own custom "UndeclaredDBProviderException" as you want to capture that a null parameter was passed to the function.

I would also suggest you run the code through FxCop and fix any errors.

Context

StackExchange Code Review Q#2601, answer score: 3

Revisions (0)

No revisions yet.