I've created a method that I'd like to unit test with NUNIT:
public void dea(Guid pguid, string serialNumber)
{
var connectionString = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
if (!string.IsNullOrEmpty(connectionString))
{
using (var con = new SqlConnection(connectionString))
{
try
{
con.Open();
var cmd = new SqlCommand("spdea", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@pguid", pguid);
cmd.Parameters.AddWithValue("@serialnumber", serialNumber);
var rowsaffected = cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
else
{
throw new ConfigurationErrorsException("Configuration string is not found.");
}
}
I want to execute several units against this method; however, it looks like I've written it in a way that does not support unit testing. For example, the SqlConnection is local to my method, and perhaps should instead be more public?
How can I rewrite this method to be more testable?
Currently, I've got the following in my unit test:
public void ExecuteNonQuery_was_called()
{
//Arrange
var consumer = new DTConsumer();
var dbCommandMock = new Mock<IDbCommand>();
dbCommandMock.Setup(dbc => dbc.ExecuteNonQuery());
var dbConnectionMock = new Mock<IDbConnection>();
dbConnectionMock.Setup(x => x.CreateCommand()).Returns(dbCommandMock.Object);
//Act
consumer.dea(It.IsAny<Guid>(), It.IsAny<string>());
//Assert
dbCommandMock.VerifyAll();
}
However, I'm off track because I think I've implemented the method in a non-testable fashion.
How can I rewrite this method to be more testable?