Reputation: 303
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
}
}
}
Upvotes: 0
Views: 1381
Reputation: 10227
Usually Unit Tests test the public "surface area" of your class.
You should design your classes in a way that you don't need to modify private variables for testing. This way, you can change the implementation changes, and still rerun your tests and see that the functionality is not broken.
Look for resources on Dependency Injection. In your example, you could pass in the connection string in a constructor to ABC or pass in an interface that ABC calls to get the connection string. You can then have a concrete class in your project that implements the interface and calls SqlConnectionManager.Instance.GetDefaultConnection();
while another instance in your test project just sets it to a hard-coded string.
Better yet, don't even connect to the database in your unit tests -- that should be stubbed out as well.
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
}
}
}
Upvotes: -1