我使用NSubstitute嘲笑和僞造。我與EF6工作,想建立數據庫上下文的SaveChangesAsync的方法來拋出異常:NSubstitute,嘗試捕獲不工作異步方法配置爲拋出異常
context.SaveChangesAsync().Throws(new DbUpdateException("", SqlExceptionHelper.CreateSqlException(2627)));
SaveChangesAsync是我的數據存儲庫的方法中調用是這樣的:
try
{
var fromDatabase = await context.Entries.OfType<Document>().FirstOrDefaultAsync(d => d.Id == doc.Id);
if (fromDatabase == null)
{
fromDatabase = new Document();
context.Entries.Add(fromDatabase);
}
PatchEntity(fromDatabase, doc);
await context.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
var innerException = ex.InnerException as SqlException;
if (innerException != null && innerException.Number == 2627)
{
errors.Add(new DbValidationError(nameof(doc.Name), "A entry with the same Name already exists under the selected parent."));
}
}
這是我的單元測試中的行:
var result = await repository.TryAddOrUpdateDocument(doc);
不幸的是我的測試保持與失敗的原因,我的測試方法拋出異常,我想C(!) ATCH。添加一個通用異常catch塊也不起作用,這個異常根本沒有被捕獲。例外是冒泡。
我的測試被聲明爲「公共異步任務...」,但將其變爲簡單無效並調用。結果對我的倉庫的異步方法也沒有幫助。到底是怎麼回事?
謝謝,疑難雜症! –