2016-08-02 77 views
-1

内例外,我有一个单元测试,是这样的:我的单元测试是不是抓我控制器操作

[Test] 
public void ThingController__Put__when_thing_is_invalid__then__throws() 
{ 
    var controller = this.CreateThingController(); 

    try 
    { 
     var r = controller.Put("thing1", this.CreateInvalidThing()); 
    } 
    catch(HttpResponseException hrex) when (hrex.Response.StatusCode == HttpStatusCode.BadRequest) 
    { 
     return; // implicit pass. 
    } 
    catch(Exception ex) 
    { 
     Assert.Fail($"Wrong exception {ex.GetType().Name}"); 
    } 

    Assert.Fail("No exception thrown!"); 
} 

但它总是命中最后Fail,即不会抛出异常。我已经打开了第一次机会异常,并可以看到它被抛出,并一直重新出现。它一直在冒泡。

注:SO检举这个的

Unit testing async method for specific exception

这个问题可能重复的是如何做,但是这个人是一个问题的解决方案,专门针对为什么catch没有被击中,即你知道如何,但犯了一个常见的错误,忘记行动是异步的 - 因为他们通常没有Async后缀 - 并需要展开。

+1

(http://stackoverflow.com/questions/12837128/unit-testing-async-method-for-specific-exception)为特定异常单元测试异步方法]的可能的复制 –

回答

3

如果您的Put方法是异步任务方法,我怀疑它是基于您描述的问题,您可以修改您的测试方法以通过制作签名异步任务来适当地处理异步/等待。如果您的Put方法是异步任务,它将作为一个热门任务执行,但由于当前未等待您的单元测试线程继续运行,因此您的异常实际上会被提升。本质上,原始代码正在创建一个消防和忘记的场景。

[Test] 
public async Task ThingController__Put__when_thing_is_invalid__then__throws() 
{ 
    var controller = this.CreateThingController(); 

    try 
    { 
     var r = await controller.Put("thing1", this.CreateInvalidThing()); 
    } 
    catch(HttpResponseException hrex) when (hrex.Response.StatusCode == HttpStatusCode.BadRequest) 
    { 
     return; // implicit pass. 
    } 
    catch(Exception ex) 
    { 
     Assert.Fail($"Wrong exception {ex.GetType().Name}"); 
    } 

    Assert.Fail("No exception thrown!"); 
} 
+0

注意:最近的测试框架支持这一点,但如果工作在旧项目中,您可能仍需要检查您的版本。 –

0

Put操作方法是异步的吗?

如果是这样,那么您不访问该操作的结果,并且该异常未被“解包”。

您应该要么调用r.ExecuteAsync(...)如果一个IHttpActionResult,或号召下加入r.Wait();Put(...)

您可能还需要更改您的catch块以捕获AggregateException并检查它。

+1

相反的r的.Wait()',你应该使单元测试'async'并使用'await r'。那么你将不必处理'AggregateException'。 – svick

+0

不能不同意这一点。另请参阅http://stackoverflow.com/questions/12191831/how-do-i-test-an-async-method-with-nunit-eventually-with-another-framework –