本文介绍了在MSTest的,怎么可以用我核实确切的错误信息[的ExpectedException(typeof运算(ApplicationException的))]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用MSTest的我怎么能确认从测试方法来确切的错误信息?我知道 [的ExpectedException(typeof运算(ApplicationException的),错误味精)] 不比较来自我的测试方法来的错误信息,但在其他单元测试框架它在做什么。

Using MSTest how can I verify the exact error message coming from a test method? I know [ExpectedException(typeof(ApplicationException), error msg)] doesn't compare the error message coming from my test method, though in other unit test framework it is doing.

解决这个问题的方法之一是使用一些try catch块写我的单元测试,但我又需要写4行以上。

One way to solve this problem is to write my unit test using some try catch block, but again I need to write 4 lines more.

有没有检查错误信息任何聪明的方法。

Is there any smartest way to check the error message.

干杯,
Pritam

Cheers,Pritam

推荐答案

您可以在那里你可以断言例外被抛出的消息。

You can create your own ExpectedException attribute where you can Assert the message of the Exception that was thrown.

code

namespace TestProject
{
    public sealed class MyExpectedException : ExpectedExceptionBaseAttribute
    {
        private Type _expectedExceptionType;
        private string _expectedExceptionMessage;

        public MyExpectedException(Type expectedExceptionType)
        {
            _expectedExceptionType = expectedExceptionType;
            _expectedExceptionMessage = string.Empty;
        }

        public MyExpectedException(Type expectedExceptionType, string expectedExceptionMessage)
        {
            _expectedExceptionType = expectedExceptionType;
            _expectedExceptionMessage = expectedExceptionMessage;
        }

        protected override void Verify(Exception exception)
        {
            Assert.IsNotNull(exception);

            Assert.IsInstanceOfType(exception, _expectedExceptionType, "Wrong type of exception was thrown.");

            if(!_expectedExceptionMessage.Length.Equals(0))
            {
                Assert.AreEqual(_expectedExceptionMessage, exception.Message, "Wrong exception message was returned.");
            }
        }
    }
}

用法

[TestMethod]
[MyExpectedException(typeof(Exception), "Error")]
public void TestMethod()
{
    throw new Exception("Error");
}

这篇关于在MSTest的,怎么可以用我核实确切的错误信息[的ExpectedException(typeof运算(ApplicationException的))]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 07:24