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

前端 未结 11 1509
南方客
南方客 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:50

    Use this little helper class:

    public static class ExceptionAssert
    {
        public static void Throws(Action action, string message)
            where TException : Exception
        {
            try
            {
                action();
    
                Assert.Fail("Exception of type {0} expected; got none exception", typeof(TException).Name);
            }
            catch (TException ex)
            {
                Assert.AreEqual(message, ex.Message);
            }
            catch (Exception ex)
            {
                Assert.Fail("Exception of type {0} expected; got exception of type {1}", typeof(TException).Name, ex.GetType().Name);               
            }
        }
    }
    

    Usage:

    Foo foo = new Foo();
    foo.Property = 42;
    
    ExceptionAssert.Throws(() => foo.DoSomethingCritical(), "You cannot do anything when Property is 42.");
    

    The advantage of explicit catching exceptions is that teh test does not succeed when another member (e.g. during the initialization) throws the exception.

提交回复
热议问题