如何使用Assert。抛出以断言异常的类型和实际的消息措辞?
就像这样:
Assert.Throws<Exception>(
()=>user.MakeUserActive()).WithMessage("Actual exception message")
我正在测试的方法抛出了多个具有不同消息的相同类型的消息,我需要一种方法来测试是否根据上下文抛出了正确的消息。
如何使用Assert。抛出以断言异常的类型和实际的消息措辞?
就像这样:
Assert.Throws<Exception>(
()=>user.MakeUserActive()).WithMessage("Actual exception message")
我正在测试的方法抛出了多个具有不同消息的相同类型的消息,我需要一种方法来测试是否根据上下文抛出了正确的消息。
当前回答
您现在可以使用ExpectedException属性,例如:
[Test]
[ExpectedException(typeof(InvalidOperationException),
ExpectedMessage="You can't do that!"]
public void MethodA_WithNull_ThrowsInvalidOperationException()
{
MethodA(null);
}
其他回答
对于那些使用NUnit 3.0约束模型并在这里结束的人:
Assert.That(() => MethodUnderTest(someValue), Throws.TypeOf<ArgumentException>());
您现在可以使用ExpectedException属性,例如:
[Test]
[ExpectedException(typeof(InvalidOperationException),
ExpectedMessage="You can't do that!"]
public void MethodA_WithNull_ThrowsInvalidOperationException()
{
MethodA(null);
}
我最近遇到了同样的事情,并建议将这个函数用于MSTest:
public bool AssertThrows(Action action) where T : Exception
{
try {action();
}
catch(Exception exception)
{
if (exception.GetType() == typeof(T))
return true;
}
return false;
}
用法:
Assert.IsTrue(AssertThrows<FormatException>(delegate{ newMyMethod(MyParameter); }));
在Assert中有更多关于发生特定异常的信息(Assert。抛出MSTest)。
Assert.That(myTestDelegate, Throws.ArgumentException
.With.Property("Message").EqualTo("your argument is invalid."));
一个真正有效的解决方案:
public void Test() {
throw new MyCustomException("You can't do that!");
}
[TestMethod]
public void ThisWillPassIfExceptionThrown()
{
var exception = Assert.ThrowsException<MyCustomException>(
() => Test(),
"This should have thrown!");
Assert.AreEqual("You can't do that!", exception.Message);
}
这可以使用Microsoft.VisualStudio.TestTools.UnitTesting;。