MOQ - verify exception was thrown

前端 未结 7 1916
暗喜
暗喜 2021-01-07 16:22

I working with MOQ framework for my testing. I have a scenario in which I expect a fault exception to be thrown. How can I verify it was thrown?

public void          


        
7条回答
  •  南方客
    南方客 (楼主)
    2021-01-07 17:04

    An old question but no source code actually showing what the solution was, so here's what I did:

    var correctExceptionThrown = false;
    
    try
    {
        _myClass.DoSomething(x);
    }
    catch (Exception ex)
    {
        if (ex.Message == "Expected message")
            correctExceptionThrown = true;
    }                    
    
    Assert.IsTrue(correctExceptionThrown);
    

    Note rather than checking the message, you can catch a particular type of exception (generally preferable).

提交回复
热议问题