Reputation: 65
Could any one suggest how to write unit test method for this method?
public virtual void OpenDatabaseConnection(string connectionString)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
}
}
Upvotes: 0
Views: 3866
Reputation: 7419
You could inject a connection factory of some sorts (e.g., Func<IDbConnection>
), make it return a mock, and then assert that Open()
and Dispose(
) were called on the mock.
And of course all that only makes sense, if you actually use the connection for anything but opening and then disposing it, as rae1 correctly pointed out in his answer.
Upvotes: 1
Reputation: 6144
Unit testing is to test your code, not a third party's code. That would be part of an integration test.
However, if you personally wrote the SqlConnection
class, and would like to test that it works correctly, I would suggest mocking out the external dependencies and then verifying that the external dependency (a database driver for example) was called when you executed the Open
method.
Another note on your example: the method you show will open the connection and then Dispose
of it since you have a using
statement around it. In other words, there is no way to use the connection once opened and the method itself is a no-op to an outside caller.
Upvotes: 1