Best way to test exceptions with Assert to ensure they will be thrown

前端 未结 9 1778
悲哀的现实
悲哀的现实 2020-12-02 06:58

Do you think that this is a good way for testing exceptions? Any suggestions?

Exception exception = null;
try{
    //I m sure that an exeption will happen he         


        
9条回答
  •  甜味超标
    2020-12-02 07:52

    Unfortunately MSTest STILL only really has the ExpectedException attribute (just shows how much MS cares about MSTest) which IMO is pretty awful because it breaks the Arrange/Act/Assert pattern and it doesnt allow you to specify exactly which line of code you expect the exception to occur on.

    When I'm using (/forced by a client) to use MSTest I always use this helper class:

    public static class AssertException
    {
        public static void Throws(Action action) where TException : Exception
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead.");
                return;
            }
            Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown.");
        }
    
        public static void Throws(Action action, string expectedMessage) where TException : Exception
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex.GetType() == typeof(TException), "Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead.");
                Assert.AreEqual(expectedMessage, ex.Message, "Expected exception with a message of '" + expectedMessage + "' but exception with message of '" + ex.Message + "' was thrown instead.");
                return;
            }
            Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown.");
        }
    }
    

    Example of usage:

    AssertException.Throws(() => classUnderTest.GetCustomer(null));
    

提交回复
热议问题