In MSTest, How can I verify exact error message using [ExpectedException(typeof(ApplicationException))]

前端 未结 11 1503
南方客
南方客 2020-12-15 16:01

Using MSTest how can I verify the exact error message coming from a test method? I know [ExpectedException(typeof(ApplicationException), error msg)] doesn\'t co

11条回答
  •  自闭症患者
    2020-12-15 16:49

    The annoyance with annotations and try/catch blocks is that you don't have a clean separation between the ACT and ASSERT phases of the test. A simpler appraoch is to "capture" the exception as part of the ACT phase using a utitlity routine such as:

    public static class Catch
    {
        public static Exception Exception(Action action)
        {
            Exception exception = null;
    
            try
            {
                action();
            }
            catch (Exception ex)
            {
                exception = ex;
            }
    
            return exception;
        }
    }
    

    This allows you to do:

    // ACT
    var actualException = Catch.Exception(() => DoSomething())
    
    // ASSERT
    Assert.IsNotNull(actualException, "No exception thrown");
    Assert.IsInstanceOfType(actualException, expectedType);
    Assert.AreEqual(expectedExceptionMessage, actualException.Message);
    

提交回复
热议问题