create test harness (unit test)
I have to create test on this class. Can someone help how to do that.
public class Db {
private System.Data.SqlClient.SqlConnection myConn;
public Db(string connString)
{
myConn = new System.Data.SqlClient.SqlConnection(connString);
}
public bool Connected
{
get { return (开发者_JAVA百科myConn.State == ConnectionState.Open); }
}
public void Connect()
{
myConn.Open();
}
public void Disconnect()
{
myConn.Close();
}
}
Yes, the connection string can be passed as constructor parameter.
Regards
Yahoo
Your only dependancy (SqlConnection) is not injectable, so first thing to do is to atleast have Poor Man's Dependency Injection constructor chaining allowing SqlConnection to be passed as parameter. Other than that, I see that this class does very little but act as a wrapper for the connection. I would perhaps abstract the connection as IDbConnection, and mock it if needed, like the test for Connected method would be something like:
IDbConnection conn = mockery.CreateMock<IDbConnection>();
Expect.Call(connection.State).Return(ConnectionState.Open);
mockery.ReplayAll();
Assert.IsTrue(db.Connected);
mockery.VerifyAll();
Connect / Disconnect can be mocked in similar fashion.
精彩评论