我喜欢模拟以下内容以确保调用ExecuteNonQuery但不确定如何操作,因为我尝试过我可能有例外但无法正确实现..我正在使用Rhino Mock
using (var command = _context.Database.Connection.CreateCommand())
{
command.CommandText = @"testproc_ins";
command.CommandType = CommandType.StoredProcedure;
SqlParameter[] parameters = GetParameters(transaction);
command.Parameters.AddRange(parameters);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
答案 0 :(得分:3)
诀窍是如何安排你的代码,以便你可以用你的模拟替换真实对象。例如:
var command = CommandFactory.CreateCommand()
假设真实CommandFactory中的CreateCommand()如上所述实现_context.Database.Connection.CreateCommand()
,但在你的单元测试中,你有一个CommandFactory,它返回一个模拟。
完成所有这些后,Rhino中的模拟非常简单:
var cmd = MockRepository.GenerateStub<IDbCommand>();
// Somehow pass mock cmd to code under test. For example,
// CommandFactory here could itself be a mock, and you tell it
// to return the mock cmd you created earlier:
SomeObject.CommandFactory.Stub(c => c.CreateCommand()).Return(cmd);
// Act
// Do something
// Assert
cmd.AssertWasCalled(c => c.ExecuteNonQuery()));