0

I'm new to writing unit tests. I have used PrivateObject to access and modify the private member of a class to use it while testing.

However, if I want to access a private variable of the method that I'm testing, how can I do that. I'll not be changing any functionality, but I need to modify a variable in order to complete the unit test.

This is what I'm trying to do. In class ABC, I want to modify the dwConn as I will not be able to access the SqlConnectionManager for unit tests, but I'm able to access it when the application is running. Thanks so much for reading this. Any help reg this would be good.

public class ABCTest
{
public void MethodATest()
{
const string connectionString = @"Data Source=servername\MSSQLSERVER2008;Initial Catalog=DB1;User ID=user1;Password=pswd1";

SqlConnection sqlConn = new SqlConnection(connectionString);

PrivateObject param0 = new PrivateObject(target);
param0.SetField("dwConn", sqlConn);

actual = target.MethodA();
}
}

public Class ABC()
{
Method A()
{
SqlConnection dwConn = (SqlConnection)SqlConnectionManager.Instance.GetDefaultConnection();

using(dwconn)
{
//some stuff
}

}
}
4

1 に答える 1

0

通常、ユニット テストでは、クラスのパブリックな「表面領域」をテストします。

テストのためにプライベート変数を変更する必要がないように、クラスを設計する必要があります。このようにして、実装の変更を変更しても、テストを再実行して、機能が壊れていないことを確認できます。

依存性注入に関するリソースを探してください。あなたの例では、コンストラクターの接続文字列を ABC に渡すか、ABC が接続文字列を取得するために呼び出すインターフェイスを渡すことができます。次に、インターフェイスと呼び出しを実装するプロジェクト内に具体的なクラスを作成し SqlConnectionManager.Instance.GetDefaultConnection();、テスト プロジェクト内の別のインスタンスがそれをハードコードされた文字列に設定するだけです。

さらに良いことに、単体テストでデータベースに接続することさえしないでください。これもスタブ化する必要があります。

public class ABCTest
{
    public class TestConnectionManager : IConnectionManager
    {
        public string GetConnection()
        {
            return  @"Data Source=servername\MSSQLSERVER2008;Initial Catalog=DB1;User ID=user1;Password=pswd1";
        }
    }
    public void MethodATest()
    {
        var abc = new ABC(new TestConnectionManager());

    }
}

public interface IConnectionManager
{
    string GetConnection();
}

public class ConnectionManager : IConnectionManager
{
    public string GetConnection()
    {
        return SqlConnectionManager.Instance.GetDefaultConnection();
    }
}


public class ABC
{

    IConnectionManager connectionManager;

    public ABC(IConnectionManager cm)
    {
        connectionManager = cm;
    }


    public void A()
    {
        //create connection from connectionManager.GetConnection()

        using(dwconn)
        {
        //some stuff
        }

    }
}
于 2012-05-25T18:10:04.970 に答える