2017-03-16 50 views
0

我使用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塊也不起作用,這個異常根本沒有被捕獲。例外是冒泡。

我的測試被聲明爲「公共異步任務...」,但將其變爲簡單無效並調用。結果對我的倉庫的異步方法也沒有幫助。到底是怎麼回事?

回答

2

我認爲問題是,異常是從原來的呼叫,而不是拋出從返回Task內部作爲described here

試着這麼做:

Func<int> throwDbEx =() => { 
    throw new DbUpdateException("", SqlExceptionHelper.CreateSqlException(2627)); 
}; 
context.SaveChangesAsync().Returns(Task.Run(throwDbEx)); 
+0

謝謝,疑難雜症! –

0

我不能100%確定,但是您可能面臨的問題是,使用void return類型異步拋出的異常無法自然捕獲。閱讀節「避免異步虛空」在這裏: https://msdn.microsoft.com/en-us/magazine/jj991977.aspx 即使它不會回答你的問題,這是值得一讀反正...