我需要帮助测试以下代码
public virtual void Update(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
int iretries = 0;
bool success = false;
do
{
try
{
this.context.SaveChanges();
success = true;
}
catch (DbUpdateConcurrencyException ex)
{
// Get the current entity values and the values in the database
// as instances of the entity type
var entry = ex.Entries.Single();
var databaseValues = entry.GetDatabaseValues();
// Choose an initial set of resolved values. In this case we
// make the default be the values currently in the database: StoreWins
object resolvedValues = ResolveConcurrency(databaseValues.ToObject());
// Update the original values with the database values and
// the current values with whatever the user choose.
entry.OriginalValues.SetValues(databaseValues);
entry.CurrentValues.SetValues(resolvedValues);
// give up after n retries
if (++iretries == NUMBER_OF_CONC_RETRIES)
throw;
}
catch (Exception)
{
//rethrow
throw;
}
} while (!success);
}
我想对DbUpdateConcurrencyException
分支进行单元测试。
因此,一个简单的测试场景是:
- 创建一个新的
DbUpdateConcurrencyException
- 模拟
SaveChanges
抛出上述异常 - 验证是否
SaveChanges
被调用了一些NUMBER_OF_CONC_RETRIES
- 断言该
Update
方法重新抛出异常
在当前状态下,无法测试上述测试场景,我无法模拟异常以包含IEnumerable<DbEntityEntry>
单个DbEntityEntry
; 我不能嘲笑GetDatabaseValues()
, 等等。
一个简单的解决方案是插入一个新的抽象层;假设使用一个接口来抽象当前位于 catch 块中的整个代码,并提供一个什么都不做的模拟。
但是我最终会遇到想要测试该接口的实现的情况,并且最终会遇到与上述相同的问题。我怎样才能嘲笑DbUpdateConcurrencyException
,GetDatabaseValues
等
我正在使用 moq 进行模拟。
谢谢您的意见