I'm trying to unit-test my implementation of an interface, and I'm having a little difficulty successfully mocking out a SqlTransaction parameter to one of the interface methods.
Here's what the interface, and method under test that I'm interested in look like..
public class MyInterface
{
void MyMethod(SqlTransaction SharedTransaction, DateTime EventTime);
}
public class MyImplementation : MyInterface
{
public void MyMethod(SqlTransaction SharedTransaction, DateTime EventTime)
{
DateTime dtLastEventTime = DateTime.MinValue;
using(SqlCommand comm = SharedTransaction.Connection.CreateCommand())
{
comm.CommandText = SQL_GET_LAST_EVENTTIME_DEFINED_ELSEWHERE;
comm.Parameters.AddWithValue("ParamName", 123);
object oResult = comm.ExecuteScalar();
dtLastEventTime = DateTime.Parse(oResult.ToString());
}
//Do something with dtLastEventTime
}
}
I've been using Moq and various syntax approaches to mock out the Database objects and not having much luck.. (I had to do some conversion to the System.Data.Common objects in order to be able to get a little further.. DbTransaction, DbConnection, DbCommand etc).
What I'd like to know is primarily whether it's possible to mock out a transaction in this way, or whether I'm barking up the wrong tree here. Luckily I may be able to get the interface converted to use a generic DbTransaction parameter rather than the provider-specific SqlTransaction, but I'm not convinced that's why I'm having a hard time with the mocking.
Here's (and this could be completely wrong, so please correct me or comment if i'm approaching this incorretly) what I've got so far for mocking code...
var mockParams = new Mock<DbParameterCollection>();
mockParams.Setup(p => p.Add(new SqlParameter("ParamName", 123)));
var mockCommand = new Mock<DbCommand>();
mockCommand.Setup(p => p.Parameters).Returns(mockParams.Object);
var mockConnection = new Mock<DbConnection>();
mockConnection.Setup(con => con.CreateCommand()).Returns(mockCommand.Object);
var mockTrans = new Mock<DbTransaction>();
mockTrans.Setup(t => t.Connection).Returns(mockConnection.Object);
However, this seems to throw an ArgumentException on the mockCommand.Setup line.. (Invalid setup on a non-overridable member)
Does anyone have any ideas or suggestions on how I might be able to correctly unit-test this method with a mocked SqlTransaction parameter?